What is the '$0' syntax in Swift

I had a question about the $0 syntax in Swift. Haven't had a chance to use it much, however, I am working with things like filter, flatmap, and compactmap, so I see them more often. Any documentation reference or resources on these topics would be super helpful in understanding!


Thanks!

Accepted Reply

$0 is a shortcut to mean "first argument" in a closure.


So, consider


let digits = [1,4,10,15]
let even = digits.filter { $0 % 2 == 0 }
let odd = digits.filter { val in val % 2 == 1 }
print("even", even)
print("odd", odd)


will produce

even [4, 10]

odd [1, 15]


So, the following are equivalent:

- long form, where everything is explicitely expressed

let even = digits.filter { (val: Int) -> Bool in return val % 2 == 0 }

The closure takes an Int parameter and return a Bool to tell is item must be filtered in


- a bit shorter, return not needed with a single expression in the 'in'

let even = digits.filter { (val: Int) -> Bool in val % 2 == 0 }


- As the type returned by the closure can be inferred, we can omit:

let even = digits.filter { (val: Int) in val % 2 == 0 }


- idem, type of argument is inferred from the type of digits items ([Int], so we can simplify further

let even = digits.filter { val in val % 2 == 0 }


- and finally, instead of naming the argument and calling in, we can express the shortest, replacing by $0:

let even = digits.filter { $0 % 2 == 0 }


Should read the Swift Reference (search for closure)

Replies

$0 is a shortcut to mean "first argument" in a closure.


So, consider


let digits = [1,4,10,15]
let even = digits.filter { $0 % 2 == 0 }
let odd = digits.filter { val in val % 2 == 1 }
print("even", even)
print("odd", odd)


will produce

even [4, 10]

odd [1, 15]


So, the following are equivalent:

- long form, where everything is explicitely expressed

let even = digits.filter { (val: Int) -> Bool in return val % 2 == 0 }

The closure takes an Int parameter and return a Bool to tell is item must be filtered in


- a bit shorter, return not needed with a single expression in the 'in'

let even = digits.filter { (val: Int) -> Bool in val % 2 == 0 }


- As the type returned by the closure can be inferred, we can omit:

let even = digits.filter { (val: Int) in val % 2 == 0 }


- idem, type of argument is inferred from the type of digits items ([Int], so we can simplify further

let even = digits.filter { val in val % 2 == 0 }


- and finally, instead of naming the argument and calling in, we can express the shortest, replacing by $0:

let even = digits.filter { $0 % 2 == 0 }


Should read the Swift Reference (search for closure)

>Any documentation reference or resources


Swift.org would be my first stop in these examples.


Have fun!

Ref: Apple Inc. « The Swift Programming Language (Swift 5). » Apple Books.

Thanks! Heading to the Swift Reference to study up on this.