Search code examples
swiftparametersclosuresfunction-call

How to call a parameter label of type closure (Swift)


Closures As Parameters

let driving = {
    print("I'm driving in my car.")
}

func travel(action: () -> Void) {
    print("I'm getting ready to go.")
    action()
    print("I arrived!")
}

travel(action: driving)

action is a parameter label. How come we consider it as a function call as in action()?


Solution

  • Lets look at a brief example:

    func myFunction() {...} Swift sees this as () -> Void

    the same way that Swift sees this "John" as String

    So when you write a function like myFunction you could really say

    func myFunction() -> Void {...} for the same result.

    Now action is defined as a parameter as a function but the type that it accepts for that parameter is () -> Void aka a closure which for now you can think of just another function.

    So the line action() is just the call of that function.

    But be sure to read up on functions accepted as parameters