Swift - Type Inference in closure

Introduction

The type of the first argument of the closure function must be the same as the type of array you are sorting.

It is redundant to specify the type in the closure, as the compiler can infer that from the type of array you are using:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits,/*from  w  w  w. j av a 2s  . c o m*/
    {
       (fruit1:String , fruit2:String ) -> Bool in
           return fruit1<fruit2
    })
)

The preceding could be rewritten without specifying the type:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]

print(sorted(fruits,//from  w ww. ja v a 2 s  .c  o m
    {
         (fruit1, fruit2) in
             return fruit1<fruit2
     } )
)

If your closure has only a single statement, you can even omit the return keyword:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]

print(sorted(fruits,//w  w  w.j av a  2 s.c  o  m
     {
          (fruit1, fruit2) in
              fruit1<fruit2
     } )
)

Related Topic