Swift - Writing Closures Inline

Introduction

You can write the closure inline, which obviates the need to define a function explicitly or assign it to a variable.

Rewriting the earlier example would yield the following:


var sortedNumbers = sorted(numbers,
  {
       (num1:Int, num2:Int) -> Bool in
          return num1<num2
  }
)

As you can observe, the ascending() function name is now gone; all you have supplied is the parameter list and the content of the function.

If you want to sort the array in descending order, you can simply change the comparison operator:

let numbers =  [5,2,8,7,9,4,3,1]
var sortedNumbers = sorted (numbers,
     {
         (num1:Int, num2:Int) -> Bool in
          return num1>num2
     }
)

print(sortedNumbers)

If you want to sort a list of strings, you can write your closure as follows:


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

print(sorted(fruits,
      {
           (fruit1:String, fruit2:String) -> Bool in
              return fruit1<fruit2
      })
)

Related Topic