0Pricing
Swift Academy · Lesson

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

  1. How Type Inference Works
  2. When to Add Explicit Annotations
  3. Inference with Literals
  4. Inference in Closures
← Back to Swift Academy