let sortedNumbers = numbers.sort { $0 > $1 }
print(sortedNumbers)
Can anyone explain, what $0
and $1
means in swift?
More Sample
array.forEach {
actions.append($0)
}
let sortedNumbers = numbers.sort { $0 > $1 }
print(sortedNumbers)
Can anyone explain, what $0
and $1
means in swift?
More Sample
array.forEach {
actions.append($0)
}
It represents shorthanded arguments sent into a closure, this example breaks it down:
Swift 4:
It is shorthand argument names.
Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.
If you use these shorthand argument names within your closure expression, you can omit the closure’s argument list from its definition, and the number and type of the shorthand argument names will be inferred from the expected function type. The in keyword can also be omitted, because the closure expression is made up entirely of its body:
Here, $0 and $1 refer to the closure’s first and second String arguments.
$0
is the first parameter passed into the closure.$1
is the second parameter, etc. That closure you showed is shorthand for:Swift 4.2
As you know, a Closure that's very close to a Lambda Function, or a Small Anonymous Function, is a self-contained block of functionality that can be passed around and used in your code. Closure has different names in other programming languages as well as slight differences in meaning – it's Lambda in Python and Kotlin or Block in C and Objective-C.
Let's see how Closure works using Shorthand Argument Names:
1. Normal Function
2. Closure Expression
3. Inline Closure Expression
4. Inferring Type From Context
5. Implicit Returns from Single-Expression Closures
6. Shorthand Argument Names
7. Operator Methods
Without Shorthand Argument Names:
With Shorthand Argument Names:
Body of this closure is short and easy to understand:
Hope this helps.
The refer to the first and second arguments of sort. Here,
sort
compares 2 elements and order them. You can look up Swift official documentation for more info: