Inference in Closures
Understand parameter and return inference in closures.
Closures Infer Types
Inside many contexts, a closure can infer both its parameter and return types from how it is used.
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled)Inferred Parameter Type
When you pass a closure to map, the element type tells Swift what $0 is, so you can omit the parameter type.
let names = ["ada", "bob"]
let upper = names.map { $0.uppercased() }
print(upper)All lessons in this course
- How Type Inference Works
- When to Add Explicit Annotations
- Inference with Literals
- Inference in Closures