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
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!
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!
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
Top comments (0)