DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on • Updated on

Day 7 : 100DaysOfSwift🚀

Day 7
Closures Part 2
Using closures as parameters when they accept parameters

A closure you pass into a function can also accept its own parameters.

We’ve been using () -> Void to mean “accepts no parameters and returns nothing”, but you can go ahead and fill the () with the types of any parameters that your closure should accept.

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

travel { (place: String) in
    print("I'm going to \(place) in my car")
}

Output:
I'm getting ready to go.
I'm going to London in my car
I arrived!
Using closures as parameters when they return values
Enter fullscreen mode Exit fullscreen mode

We’ve been using () -> Void to mean “accepts no parameters and returns nothing”, but you can replace that Void with any type of data to force the closure to return a value.

func travel(action: (String) -> String) {
    print("I'm getting ready to go.")
    let description = action("London")
    print(description)
    print("I arrived!")
}

travel { (place: String) -> String in
    return "I'm going to \(place) in my car"
}

Output:
I'm getting ready to go.
I'm going to London in my car
I arrived!
Enter fullscreen mode Exit fullscreen mode

Closures with multiple parameters

func travel(action: (String, Int) -> String) {
    print("I'm getting ready to go.")
    let description = action("London", 60)
    print(description)
    print("I arrived!")
}

travel {
    "I'm going to \($0) at \($1) miles per hour."
}

Output:
I'm getting ready to go.
I'm going to London at 60 miles per hour.
I arrived!
Enter fullscreen mode Exit fullscreen mode

Returning closures from functions

func travel() -> (String) -> Void {
    return {
        print("I'm going to \($0)")
    }
}

let result = travel()
result("London")

Output:
I'm going to London
Enter fullscreen mode Exit fullscreen mode

Top comments (0)