Swift - Assigning Closures to Variables

Introduction

Swift functions are special types of closures.

In fact, a closure is a function without a name.

However, you can assign a closure to a variable.

For example, the ascending() function can be written as a closure assigned to a variable:


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

The preceding code declares that it is a closure that takes two Int arguments and returns a Bool value:

var compareClosure :  (Int, Int)->Bool  =

The actual implementation of the closure is then defined:

{
    (num1:Int, num2:Int) -> Bool in
        return num1 < num2
}

To use the compareClosure closure with the sorted() function, pass in the compareClosure variable:

Demo

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


let numbers =  [5,2,8,7,9,4,3,1]
var sortedNumbers = sorted (numbers, compareClosure)


print(numbers)/*from  w  w  w .  j a v  a  2 s .c  om*/
print(sortedNumbers)

In general, a closure has the following syntax:

{
   ([ parameters       ])  ->   [return type ] in
        [statements]
}

Related Topic