Group Group Group Group Group Group Group Group Group

Programming in Swift: Functions and Types · Challenge: Closures | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5429279-programming-in-swift-functions-and-types/lessons/11

I don’t understand the part about things that can only be done in a closure instead of a function. The Pythagorean theorem example shows
printResult({ (a, b) -> Double in
ab
}, 3, 4)
But can’t this be done with the following function?
func pythagorean(a: Double, b: Double) -> Double {
return ((a
a) + (b*b)).squareRoot()
}
pythagorean(a: 5, b: 3)

1 Like

Hi! You can certainly do that exact thing with a function. What you can’t do is call pythagorean and tell it to do something else with its parameters.

With a higher-order function like printResult, you can call the same function multiple times, but ask it to perform different operations each time via the closure. Hopefully you’ve continued watching this part of the course and have seen how useful that can be with map and other collection methods!

In the Closures challenge - 1st sub-challenge I had a problem with the expression
lastName ?? “”
It was covered in one of the previous lessons but I couldn’t review all of them to find the answer . It has to do something with unwrapping optionals .
In case someone else has the same problem …
It is called Nil coalescing

In Challenge one you have the function and closure having the same name. Initially I thought you are overloading the function - but this is not the case. Upon experimenting it seems that you can have a variable that has the same name as a function! Hence the variable storing the closure simply has the same name of the function and is not overloading it with a different parameter names.

Swift if supposed to be focused on clarity - having the ability to have a variable the same name as a function seems like a mistake to me. (It seems the namespaces will clash if there are no arguments in a function that shares the name with a variable or constant)