Hello All,
As I'm mixing my education from Paul's books, internet sources and 100 Days of SwiftUI, I tend to return to the topics where I believe I need more practice with the basics. Closures are one of those topics and I'm trying to re-educate myself after 2+ years with Java. I'm wondering if you could help me catch what's happening with the code from question 8/12 from the Test:
func getDirections(to destination: String, then travel: ([String]) -> Void) {
let directions = [
"Go straight ahead",
"Turn left onto Station Road",
"Turn right onto High Street",
"You have arrived at \(destination)"
]
travel(directions)
}
getDirections(to: "London") { (directions: [String]) in
print("I'm getting my car.")
for direction in directions {
print(direction)
}
}
It's a valid code, but is it the most optimal one? Could someone tell me how to interpet what's happening there? My understanding:
- We create getDirections function that accepts String and a closure as parameters. The closure accepts an Array of Strings and returns nothing (Void).
- The closure inside function accepts the directions array and uses functions destination parameter
- getDirections function gets called, we declare "London" as a destination -> here's where I'm confused
I'm not exactly sure if that's the way to handle it, but I would prefer function getDirections to handle everything and be handled with a simple call of getDirections(to: "London").
Any hints how to redirect my mindset will be highly appreciated! :)