Optionals
Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.
Code
import Foundation
// Optional declaration
let name: String? = "Alice"
let missing: String? = nil
// Optional binding
if let actual = name {
print("Hello, \(actual)")
}
// Multiple binding
if let first = name, let second = missing {
print("\(first) and \(second)")
} else {
print("at least one is nil")
}
// Nil-coalescing operator
let value = missing ?? "default"
print(value)
// Optional chaining
struct User { var address: Address? }
struct Address { var city: String }
let user = User(address: Address(city: "Paris"))
print(user.address?.city ?? "unknown")
// Guard statement for early exit
func greet(_ who: String?) {
guard let who else { print("no name"); return }
print("Hi \(who)")
}
greet(name)Explanation
Optionals wrap a value or nil, forcing the compiler to track the absence of a value explicitly. if let and guard let safely unwrap and branch, while ?? supplies a default. Optional chaining short-circuits the whole expression to nil as soon as any link is nil.
More Swift Snippets
Closures
Define closure expressions, capture state, and pass escaping callbacks.
Protocols
Define contracts, conform with structs, and add default behavior via extensions.
Generics
Write type-parameterized functions and types with protocol constraints.
Structs and Classes
Compare value-type structs with reference-type classes and inheritance.
Error Handling
Throw and catch typed errors with do-catch, try?, try!, and rethrows.
Concurrency (async/await)
Run async functions, parallelize with async let, and fan out with task groups.