Closures
Define closure expressions, capture state, and pass escaping callbacks.
Code
import Foundation
// Closure expression
let add: (Int, Int) -> Int = { a, b in a + b }
print(add(2, 3))
// Trailing closure syntax
let doubled = [1, 2, 3].map { $0 * 2 }
print(doubled)
// Sorted with closure
let sorted = [3, 1, 2].sorted(by: >)
print(sorted)
// Capture semantics
func makeCounter() -> () -> Int {
var count = 0
return { count += 1; return count } // captures by reference
}
let counter = makeCounter()
print(counter(), counter(), counter()) // 1 2 3
// Escaping closure stored for later
class Loader {
var completions: [(String) -> Void] = []
func register(_ block: @escaping (String) -> Void) {
completions.append(block)
}
func fire() { completions.forEach { $0("done") } }
}
let loader = Loader()
loader.register { msg in print("got \(msg)") }
loader.fire()Explanation
Closures are self-contained blocks of functionality that capture their surrounding scope. Trailing closure syntax makes higher-order calls like map and sorted read naturally. @escaping marks closures that outlive the function they are passed to, which the compiler requires for stored callbacks.
More Swift Snippets
Optionals
Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.
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.