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

后端 未结 6 2379
你的背包
你的背包 2020-12-12 12:12
let sortedNumbers = numbers.sort { $0 > $1 }
print(sortedNumbers)

Can anyone explain, what $0 and $1 means in swift?

6条回答
  •  误落风尘
    2020-12-12 12:30

    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.

提交回复
热议问题