Swift: Can someone explain this syntax `numbers.sort { $0 > $1 }` for me?

后端 未结 4 2134
慢半拍i
慢半拍i 2020-12-09 00:01

First of all, this question is not about \"what does $0 mean\". I learnt in swift document that $0 is like index.

My question is \"How numbers.sort { $0 >

4条回答
  •  臣服心动
    2020-12-09 01:01

    From developer.apple.com

    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.

提交回复
热议问题