Tracks
/
Swift
Swift
/
Syllabus
/
Shorthand arguments
Sh

Shorthand arguments in Swift

1 exercise

About Shorthand arguments

If the types of the parameters can be inferred, Swift also allows the parameter names and the keyword in to be omitted from the closure definition. The parameters can instead be referred to using a special shorthand syntax, where $0 refers to the first parameter, $1 refers to the second, and so on.

let mean: (Double, Double) -> Double = { $0 + $1 / 2.0 }

["apple", "ball", "carrot"].sorted(by: { $0.count < $1.count })

This style is most often used when passing closures into higher-order functions and brevity is valued.

Edit via GitHub The link opens in a new window or tab

Learn Shorthand arguments