Lesson 42Closures

Closure Syntax

Shorthand Syntax

Swift provides several ways to write closures more concisely. Let's see the progression from verbose to super short!

Syntax Evolution

1. Full{ (a: Int, b: Int) -> Bool in return a < b }
2. Inferred Types{ (a, b) in return a < b }
3. Implicit Return{ (a, b) in a < b }
4. Shorthand Args{ $0 < $1 }
5. Operator(<)

Shorthand Arguments

Use $0, $1, $2... for parameters:

  • $0 - First parameter
  • $1 - Second parameter
  • $2 - Third parameter, etc.

When to Use Each

  • Full syntax - Complex, multi-line closures
  • $0, $1 - Simple one-liners
  • Operators - When you just need the operator
main.swift
// FULL CLOSURE SYNTAX
let fullClosure = { (a: Int, b: Int) -> Int in
    return a + b
}

// SHORTHAND SYNTAX - Swift can infer types!

// 1. INFERRED RETURN TYPE
let numbers = [5, 2, 8, 1, 9]

// Full syntax
let sorted1 = numbers.sorted(by: { (a: Int, b: Int) -> Bool in
    return a < b
})

// 2. INFERRED PARAMETER TYPES
let sorted2 = numbers.sorted(by: { (a, b) -> Bool in
    return a < b
})

// 3. INFERRED RETURN (single expression)
let sorted3 = numbers.sorted(by: { (a, b) in
    a < b
})

// 4. SHORTHAND ARGUMENT NAMES ($0, $1, $2...)
let sorted4 = numbers.sorted(by: { $0 < $1 })

// 5. OPERATOR METHODS (ultimate shorthand!)
let sorted5 = numbers.sorted(by: <)

// All of these produce the same result!
print(sorted5)  // [1, 2, 5, 8, 9]

// MORE EXAMPLES WITH MAP

// Full syntax
let doubled1 = numbers.map({ (num: Int) -> Int in
    return num * 2
})

// Shorthand
let doubled2 = numbers.map { $0 * 2 }

print(doubled2)  // [10, 4, 16, 2, 18]

// FILTER with shorthand
let evens = numbers.filter { $0 % 2 == 0 }
print(evens)  // [2, 8]

// REDUCE with shorthand
let sum = numbers.reduce(0) { $0 + $1 }
print(sum)  // 25

// Or even shorter!
let sum2 = numbers.reduce(0, +)

// CHAINING with shorthand
let result = numbers
    .filter { $0 > 3 }
    .map { $0 * 2 }
    .sorted()
print(result)  // [10, 16, 18]

Try It Yourself!

Rewrite this using shorthand: numbers.filter({ (n: Int) -> Bool in return n > 5 })