Swift - Function Trailing Closures

Introduction

Consider the closure that you saw earlier:

Demo

var fruits = ["orange", "apple", "Json", "Database", "pineapple"]
print(sorted(fruits,//from  www  .  ja  v  a2s.  c o m
     {
         (fruit1:String, fruit2:String) -> Bool in
             return fruit1<fruit2
     } )
)

The closure is passed in as a second argument of the sorted() function.

If the closure is the final argument of a function, you can rewrite this closure as a trailing closure.

A trailing closure is written outside of the parentheses of the function call.

The preceding code snippet when rewritten using the trailing closure looks like this:

Demo

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

Using the shorthand argument name, the closure can be shortened to the following:

Demo

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

Related Topic