Home » Swift » What does $0 and $1 mean in Swift Closures?

What does $0 and $1 mean in Swift Closures?

Posted by: admin November 30, 2017 Leave a comment

Questions:
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)
}
Answers:

$0 is the first parameter passed into the closure. $1 is the second parameter, etc. That closure you showed is shorthand for:

let sortedNumbers = numbers.sort { (firstObject, secondObject) in 
    return firstObject > secondObject
}

Questions:
Answers:

It represents shorthanded arguments sent into a closure, this example breaks it down:

Swift 3.1:

var add = { (arg1: Int, arg2: Int) -> Int in
    return arg1 + arg2
}
add = { (arg1, arg2) -> Int in
    return arg1 + arg2
}
add = { arg1, arg2 in
    arg1 + arg2
}
add = {
    $0 + $1
}

let result = add(20, 20) // 40

Questions:
Answers:

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:

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.

Questions:
Answers:

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:

    reversed = names.sort( { $0 > $1 } )

Here, $0 and $1 refer to the closure’s first and second String arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *