How To Use Swift Closures Example

Swift closures is a kind of code block which can be used as a function, function return type or other function’s parameters. It can has parameters and return values, or it can also do not has parameter and return nothing. It make writing swift code clean and clear, it can save a lot of coding time. But for swift beginners, swift closures may make you confused because of the coding style and grammar. This article will give you some swift closures example to make you understand it.

There are three kind of swift closures, they are:

  1. Global function : Has function name but can not capture any context variable value.
  2. Nested function : Has function name and can capture context variable values inside the up level function only.
  3. Closure expression : Light weight swift closure which do not has name, can capture variable values according to context environment.

1. How To Define A Swift Closure.

Define a swift closure is very simple, the syntax is something like below.

{ (parameter_1, parameter_2, ......) -> return type in
    
    statements
}

Below is a swift closure example, from this example we can see that swift closure start with { and end with },  it has 2 Int type parameters, and the return type is Int also. The code behind keyword in is the swift closure code body, when the closure execute, it will execute the source code after keyword in.

{ ( num1: Int, num2: Int) -> (Int) in
  
      return num1 + num2
}
  1. parameters : The parameters is a parameter list separated by , which will be passed to the swift closure from outside. If the closure do not need parameters, then just pass empty tuple like this.
    () -> (String)
  2. return type : This can be any swift data type, if the closure do not return data, then you can use Void or ().
    (str:String) -> Void
    
    or
    
    (str:String) -> ()
  3. in : This is the swift closure statement keyword, the code after this keyword is the swift closure body, the body will be executed when this swift closure execute.

2. Swift Closure Example.

2.1 Use Closure For Array Sorted Method.

This example will define a swift closure which is used by a string array object’s sorted method. The closure’s function is to compare two sibling elements and then return a boolean value to tell the array which element should be placed first. If do not use swift closure, you need to define a function to implements same feature.

  1. Below example will define a function to implement elements compare in a string array, and show the result ascend.
    // Define a string array.
    let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]
    
    // Define a function that is used to compare two string and return a boolean value.
    func elementCompare(ele1: String, ele2: String) -> Bool{
        
        if(ele1 < ele2){
            return true
        }else{
            return false
        }
    }
    
    /* Invoke the arr's sorted method, pass above elements compare function to it.
       The sorted method will return a new array which array elements will be ordered ascend.
     */
    var newArr = arr.sorted(by: elementCompare)
    
    print(newArr)
    
    

    Below is above code execution result.

    ["Android", "Linux", "MacOS", "Windows", "iOS"]
  2. Below code will implement same array elements compare function as above use swift closure. The swift closure start with { and end with }. Below example will order the array elements descend.
    // Define a string array.
    let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]
    
    /* Invoke the arr's sorted method, pass a swift closure to it.
     The sorted method will return a new array which array elements will be ordered descend.
     */
    var newArr = arr.sorted(by: {(ele1: String, ele2: String) -> Bool in
            
            if(ele1 > ele2){
                return true
            }else{
                return false
            }
        }
    )
    
    print(newArr)

    Below is above code execution result.

    ["iOS", "Windows", "MacOS", "Linux", "Android"]
    

2.2 Decide Parameter Type By Value Context.

Swift closure can also decide the parameter’s type by the context’s value, so you can simplify the swift closure definition code like below. In below code, you can omit closure parameter type.

// Define a string array.
let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]

// Swift closure decide the parameter's data type by arr element value.
var newArr = arr.sorted(by: { (ele1, ele2) -> Bool in
    
    return ele1 > ele2
})

print(newArr)

Above code will result below output.

["iOS", "Windows", "MacOS", "Linux", "Android"]

2.3 Single Expression Swift Closure.

You can also write swift closure in just a single expression, you can even omit the return keyword like below.

// Define a string array.
let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]

var newArr = arr.sorted(by: { (ele1, ele2) -> Bool in ele1 < ele2})

print(newArr)

Below is above code execution result.

["Android", "Linux", "MacOS", "Windows", "iOS"]

2.4 Swift Closure Parameter Place Holder.

You can refer the swift closure parameter directly use place holder $0, $1, $2 … in closure body, you do not need to define swift closure parameter in this case.

// Define a string array.
let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]

// $0 is the first parameter in swift closure, $1 is the second parameter in swift closure.
var newArr = arr.sorted(by: { $0 > $1 })

print(newArr)

Below is above code execution result.

["iOS", "Windows", "MacOS", "Linux", "Android"]

2.5 Swift Trail Closure.

If you pass a swift closure as the last parameter to a function, you can define this closure as swift trail closure. Swift trail closure is written behind the function call, not pass the closure as the function parameter.

// Define a string array.
let arr = ["iOS", "Linux", "Android", "Windows", "MacOS"]

// Write swift closure after the function call. The closure is not passed as sorted function's parameter.
var newArr = arr.sorted(){
    
    (ele1:String, ele2:String) -> Bool in
    
    return ele1 < ele2
    
}

print(newArr)

Below is above source code execution result.

["Android", "Linux", "MacOS", "Windows", "iOS"]

2.7 Define Function That Return Swift Closure.

Swift closure can also be used as a function return type, below function will return a swift closure, and the returned swift closure is a reference type, so when you invoke the returned swift closure for the second time, it point to the same swift closure object.

/* Define a function getMultipler. The function has an Int type input parameter multipleBy.
 
   It return a swift closure ( a nested function ). The swift closure ( nested function ) do not has parameters and only return Int value. */
func getMultipler(multipleBy amount:Int) -> () -> Int{

    var totalValue = 1
    
    // Define a nested function. The function has no parameters and return Int value.
    func multipler() -> Int{
        
        // Multiple totalValue by input amount.
        totalValue *= amount
        
        // This nested function return this value.
        return totalValue
    }
    
    // Return above nested function.
    return multipler

}

// Get a multipler with above function. The returned multipler is a nested function.
let multiplerBy3 = getMultipler(multipleBy: 3)

// Print the multipler value twice. Because swift closure is reference type data, so the second invoke will run the same swift closure object.
print(multiplerBy3())

print(multiplerBy3())

Below is above code execution result.

3
9

3. Define Aliases For Swift Closure Using typealias.

typealias is a keyword used in Swift to redefine the name of an existing type (similar to typedef in Objective C syntax). It can give a new name to replace the previous type, and make the code clearer, easier to understand.

READ :   iOS Swift Array Example

The use of typealias is simple: just use = to assign a value. Now we will use swift typealias keyword to define a name to swift closure, then we can use the name to refer the swift closure.

// Define a type alias for swift closure definition.
typealias Multiple = (_ x: Int, _ y: Int) -> (Int)

// Declare a constant variable of above type alias.
let multipleClosure1 : Multiple

// Implement above swift closure code to the constant variable.
multipleClosure1 = {

    (x: Int, y: Int) -> (Int) in
    
    return x * y
    
}

// Invoke the closure and get the result
let result = multipleClosure1(2, 3)

// Print result in console output.
print(result)

Below is above code execution result.

6

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.