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. ja va 2  s .  c  o 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  w  w.  jav a2s  .c om
       {
         $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