Swift Blocks Tutorial – iOS Swift Closures

In iOS Swift Blocks (Closures) Tutorial, I have explained about iOS Swift Closures (Blocks) syntax, features and usage with examples.

Swift Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks Objective-C and have some extra features.

Below are topics covered in this article:
1) Swift Blocks (Closures) Syntax
2) Declaring Swift Closures
3) Passing blocks as function arguments


1) Swift Blocks (Closures) Syntax

Closures can use constant parameters,variables,and in-out parameters similar to functions. Closures stars with { and ends with }.

{ (Parameters) -> ReturnType in
    statements
}

Note: in is a keyword


2) Declaring Swift Closures

Below is a simple swift block, without any arguments and without return value.

        var clos1 = {
            () -> Void in
            
            println("Simple Closure")
        }
        
        clos1()

Blocks with arguments and without any return value

 var print1 =
 {
     (str:String) -> Void  in

     println(str)
     
 }
 
 print1("Ravi")

Blocks with arguments and with return values.

var max = {
    (num1:Int,num2:Int) ->  Int in
    
    return num1 > num2 ? num1 : num2
}

println("Max of 10,2 : \(max(10,2))")

3) Passing blocks as function arguments

You can pass blocks as function parameters similar to objective-C.

To discuss more about Swift Blocks features,Let us take an example mySort() function which takes integer array return sorted array using comparator.

func mySort(inout numbers:Int[],compare:((Int,Int)->Bool))
 {
        //Write your login  to sort numbers using comparator method
            var tmp:Int
            var n = numbers.count
            
            for(var i=0;i<n;i++)
            {
                for(var j=0;j<n-i-1;j++)
                {
                    if(numbers[j] > numbers[j+1])
                    {
                        tmp=numbers[j];
                        numbers[j]=numbers[j+1];
                        numbers[j+1]=tmp;
                    }
                }
            }
 }
 
 var numbers = [10,1,20,123,50]

 mySort(&numbers,{
     (num1:Int,num2:Int) -> Bool in
     
     return num1 > num2
     
     })

 

Swift provides simpler way of writing closure expressions.

Inferring Type from Context:

Swift infers parameter and return value types from context. So you need not specify the return types and argument types. So the above block is simply written as

var sorted2 =  mySort(numbers,{ n1,n2 in return n1 > n2})

 

Implicit returns from single-expression closures:
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration.

var sorted3 =  mySort(numbers){ n1,n2 in  n1 > n2}

 

Shorthand argument names:

Swift provides automatically shorthand arguments. arguments are accessed by $0,$1…$n

var sorted4 =  mySort(numbers,{ $0 > $1})

 

Operator Functions:
More shorter way of writing closure expression is using operator functions.

var sorted5 =  mySort(numbers,>)

 

Trailing closure syntax:
Trailing closure is a closure expression that is written after the parenthesis of the function call.

var sorted6 =  mySort(numbers){
    (num1:Int,num2:Int) -> Bool in
    
    return num1 > num2
    
    }
    
var sorted7 = mySort(numbers) { $0 > $1}

 

Reference: Apple Documentation