Closure in iOS Swift

Closures are self contained chunks of code that can be passed around and used in your code.

Functions are a special kind of closures. There are three kinds of closures:

  • global functions – they have a name and cannot capture any values
  • nested functions (function inside another function) – they have a name and can capture values from their enclosing functions
  • closure expressions – they don’t have a name and can capture values from their context

The general syntax for declaring closures is:

{ (parameters) -> return type in
 
statements

}

If the closure does not return any value you can omit the arrow (->) and the return type. This also applies to the case where the type of the closure can be inferred.

{ (parameters) in

statements

}

How to write closure :

var noParameterAndNoReturnValue: () -> () = {
    print("Hello!")
}
noParameterAndNoReturnValue   //Hello!

var noParameterAndReturnValue: () -> (Int) = {
    return 1000
}
noParameterAndReturnValue  //1000

var oneParameterAndReturnValue: (Int) -> (Int) = { x in
    return x % 10
}
oneParameterAndReturnValue(99) //9  --we pass parameter to variable because closure has parameter 

var multipleParametersAndReturnValue: (String, String) -> (String) = 
    { (first, second) -> String in
    return first + " " + second
}
multipleParametersAndReturnValue("My","Name") //My Name

above variable  can also written as:

var noParameterAndNoReturnValue = {
    print("Hello!")
}

var noParameterAndReturnValue = {
    return 1000
}

var oneParameterAndReturnValue = { x in
    return x % 10
}

var multipleParametersAndReturnValue = 
    { (first, second) -> String in
    return first + " " + second
}

Shorthand Parameter Names

Swift provides shorthand parameter names for closures. You can refer to the parameters as $0, $1, $2 and so on. To use shorthand parameter names ignore the first part of the declaration.

How to use closure to reduce repeated code?

using closure instead function we can reuse code for similar kind of logic

without closure : 

var numbers = [2,4,5,8,9,3,7]

func evenNumbers(numbers: [Int]) -> [Int] {
    
    var evenNumbers = [Int]()
    
    for num in numbers {
        
        if num % 2 == 0 {
            evenNumbers.append(num)
        }
    }
    return evenNumbers
}
print(evenNumbers(numbers: numbers))


func numberGreaterThanFive(numbers: [Int]) -> [Int] {
    
    var evenNumberGreaterThanFive = [Int]()
    
    for num in numbers {
        
        if num > 5  {
            evenNumberGreaterThanFive.append(num)
        }
    }
    return evenNumberGreaterThanFive
}
print(numberGreaterThanFive(numbers: numbers))

Using Closure : 

var numbers = [2,4,5,8,9,3,7] 

func filerNumbers(numbers: [Int], closure: (Int) -> Bool ) -> [Int]{
    
    var filteredNumber = [Int]()
    
    for num in numbers {
        
        if closure(num) {
            
            filteredNumber.append(num)
        }
    }
    return filteredNumber
}

var evenNumbers = filerNumbers(numbers: numbers, closure: { 
(num) -> Bool in         
    return num % 2 == 0
})
print(evenNumbers)

var numberGreaterThanFive = filerNumbers(numbers: numbers, closure: { 
(num) -> Bool in 
    return num > 5
}) 
print(numberGreaterThanFive)

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

One thought on “Closure in iOS Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s