7.3. Closures as parameters

So far, we rewrote the functions as closures. So why write a closure when we can just define a function? Well, the beauty of closures is we can pass closures as parameters to a function. And iOS UIKit and SwiftUI libraries use it extensively.

Let's define two closures, one to fly and another to drive.

let drive = {
    print("I am driving!")
}

let fly = {
    print("I am taking a flight!")
}

Now let's recreate a previous scenario where the user could travel from one place to another. So we can write the function as:

//taking a closure as the parameter 'how'
func travel(from source:String, to destination:String, how: ()->Void){
    
    print("I need to travel from \(source) to \(destination).")
    how()
}

In function travel, we are accepting a closure (how) as the parameter. Notice that we are defining the data type of the parameter 'how' as ()->Void.

()->Void represents a closure data type where:

  • () means the closure won't accept any parameters, and

  • -> Void means the closure will return "nothing". Void means "nothing" in Swift.

Does the parameter data type for the closure (labeled as how) match with the definitions of the three closures we wrote before?

Now, let's call the travel function:

It will print:

See, we are calling the closure we received as the parameter how from inside the function.

When closures accept parameters themselves and return values

Let's define three closures to do addition, subtraction, and multiplication:

Now, we will write a function calculate to do some operations on two integers and return the result:

So, here we are accepting a closure and labeling it as operation. The operation closure can take two Int parameters and returns an Int.

  • (_:Int, _:Int)-> Int is a closure data type.

  • (_:Int, _:Int) means that the closure itself accepts two Int parameters. We do not need the labels for the Ints since the labels are not important when we call closures.

  • -> Int means that the closure will return an Int.

Then the function calculate takes two more Int parameters num1 and num2 and finally returns an Int. We can call the function calculate as follows:

Which prints:

So far, we have covered the basics of closures. You need to get used to the closures. I would practice writing closures as much as I could, probably just starting with writing closures deliberately for every simple function. iOS libraries use it very extensively, so again, you need to understand the idea.

Last updated

Was this helpful?