Swift Cheatsheet
Optionals
Use this Swift reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Optional basics
T? means a value of type T or nil. Non-optional types can never hold nil, which is checked at compile time.
var nickname: String? = nil nickname = "Ada" let parsed = Int("42") // Int?, the conversion can fail let missing = ["a": 1]["b"] // Int?, the key may be absent
| Pattern | Use |
|---|---|
if let x { } | Bind and use when present |
guard let x else { } | Exit early on nil, use x afterward |
x?.member | Optional chaining, nil propagates |
x ?? fallback | Default value |
x! | Force unwrap, crashes on nil |
x.map { } / x.flatMap { } | Transform without unwrapping |
while let | Loop while a producer returns values |
if let, including the shorthand
let nickname: String? = "Ada" // Swift 5.7+ shorthand: shadows the optional under the same name if let nickname { print(nickname.count) } // Classic form: rename, or bind the result of an expression if let nick = nickname, nick.count > 2 { print(nick) }
Comma-separated conditions must all succeed, and later conditions can use earlier bindings.
guard let for early exit
func firstWordLength(of line: String?) -> Int { guard let line, !line.isEmpty else { return 0 } guard let word = line.split(separator: " ").first else { return 0 } return word.count // both bindings still in scope here }
guard keeps the happy path unindented, which is the idiomatic Swift shape for validation-heavy functions.
Chaining and defaults
let length = nickname?.count ?? 0 // Int, never nil let upper = nickname?.uppercased() // String?, nil propagates let firstCell = matrix.first?.first // chains flatten, still one `?` deep user?.profile?.avatar?.load() // any nil stops the whole chain
?? evaluates its right side lazily and can chain: a ?? b ?? defaultValue.
Force unwrap and implicitly unwrapped optionals
let n = Int(readLine()!)! // fine for trusted judge input, crashes on bad data var label: UILabel! // IUO: auto-unwraps at each use, used for late-set values
Reserve ! for cases where nil is a programmer error. Production code prefers guard let with a real error path.
map, flatMap, and compactMap
let doubled = Int("21").map { $0 * 2 } // Optional(42) let positive = Int("3").flatMap { $0 > 0 ? $0 : nil } let nums = ["1", "x", "3"].compactMap(Int.init) // [1, 3], drops the nils
while let and optional patterns
while let line = readLine() { // reads stdin until EOF print(line) } let x: Int? = 5 switch x { case .none: print("nil") case .some(let v): print(v) // Optional<T> is just an enum } if case let v? = x { print(v) } // optional-pattern sugar for .some