Swift Vocabulary
5 exercises — optionals (guard let / if let), value vs reference types, retain cycles, opaque return types (some), and Swift Concurrency (actor, @MainActor).
0 / 5 completed
Swift vocabulary quick reference
- Optionals:
guard let= early exit + scoped binding;if let= conditional block;?.= optional chaining;??= nil coalescing - struct = value type (copy); class = reference type (shared);
mutating= method that modifies a struct - retain cycle — circular strong references; fix with
[weak self]in closures - some Protocol = opaque return type (static dispatch); any Protocol = existential (dynamic dispatch)
- actor — reference type with automatic state isolation;
@MainActor= main thread enforcement
1 / 5
A Swift code review says: "Always use
guard let at the top of a function instead of nested if let — it keeps the happy path unindented." What is the difference between guard let and if let for unwrapping optionals?Swift optional unwrapping vocabulary:
Optional
An optional (
The bound constant (
Force unwrap
Optional chaining
Nil coalescing
Vocabulary:
• optional — a value or nil;
• unwrap — extract the value from an optional
• golden path / happy path — the main logic flow with all conditions satisfied
• pyramid of doom — deeply nested
Optional
An optional (
String?) is a value that is either a String or nil. Before using it, you must unwrap it.if let — conditional bindingif let name = user.name {
print(name) // name is String here
}
// name not accessible outsideThe bound constant (
name) exists only inside the if block. Leads to "pyramid of doom" with multiple optionals.guard let — early exit bindingguard let name = user.name else {
return // exit early if nil
}
print(name) // name is String for the rest of functionguard requires an exit (return, throw, break, continue, or fatalError()) in the else block. The bound constant is available after the guard statement — ideal for precondition checks.Force unwrap
!user.name! — crashes with a runtime error if nil. Use only when you are 100% certain the value is non-nil (e.g., a static asset that must exist).Optional chaining
?.user.address?.city — returns nil if any value in the chain is nil, rather than crashing.Nil coalescing
??user.name ?? "Anonymous" — provide a default value if nil.Vocabulary:
• optional — a value or nil;
String?• unwrap — extract the value from an optional
• golden path / happy path — the main logic flow with all conditions satisfied
• pyramid of doom — deeply nested
if let chains