Day 7 : 100DaysOfSwift🚀
Saurabh Chavan
Posted on August 19, 2022
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
đź’– đź’Ş đź™… đźš©
Saurabh Chavan
Posted on August 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.