Swift - Closure Shorthand Argument Names

Introduction

As Swift automatically provides shorthand names to the parameters, which you can refer to as $0 , $1 , and so on.

The previous code snippet:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits,//from ww  w.  j a v  a  2s. co m
    {
         (fruit1, fruit2) in
             fruit1<fruit2
     } )
)

could be rewritten as follows without using named parameters:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits,//w ww  .  j  ava  2 s .  c o m
       {
         $0<$1
     } )
)

To make the closure really terse, you can write everything on one line:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits, { $0<$1 } ))

Related Topic