Quick Reference Swift Cheatsheet
Swift on one page — values, optionals, collections, structs and classes,
errors, memory, async, and the traps around force unwrap and string indexes.
10 sections 10 tables 14 code snippets The compiler swift hello.swift A constant and a variable let title = "Dune"
var pages = 412
pages += 1
print(title) This page is the Swift language. The samples run as a file or in a playground. Bind it before you use it let published: Int? = nil
if let year = published {
print(year)
} A stand-in let shown = published ?? 2026
print(shown) An array var books = ["Dune", "Neuromancer"]
books.append("Foundation")
print(books[0]) A dictionary let prices = ["Dune": 18.5]
let price = prices["Dune"] ?? 0
print(price) A named argument func total(price: Double, count: Int = 1) -> Double {
return price * Double(count)
}
print(total(price: 18.5, count: 2)) A struct copies struct Book {
var title: String
var pages: Int
}
var book = Book(title: "Dune", pages: 412)
book.pages = 500 Every case is covered switch pages {
case 0:
print("empty")
case 1...300:
print("short")
default:
print("long")
} A function that can fail enum LoadError: Error {
case missing
}
func load() throws -> String {
throw LoadError.missing
}
do {
let title = try load()
print(title)
} catch {
print("missing")
} A weak owner class Reader {
var name: String
init(name: String) { self.name = name }
}
class Shelf {
weak var owner: Reader?
} Suspend, then continue func fetchTitle() async -> String {
return "Dune"
}
func show() async {
let title = await fetchTitle()
print(title)
} This stops on nil let title: String? = nil
print(title!) The first character let title = "Dune"
let index = title.startIndex
print(title[index]) How to use this page: run swift hello.swift, keep title as a let, and unwrap published with if let before you print it. Then make Book a struct, and call an async function with await. |