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)

Hi, I had a question on Challenge 2.

You say, “I’ll start with printResult and let it auto-generate a closure for me.”

I understand that auto-completion will get me to this point:
printResult(operate: (Double, Double) -> Double, a: Double, b: Double)

But I don’t understand what you did to auto-generate the closure into the first argument: – scratch that. I figured it out!

As I was trying to compose this message, and copying text from Xcode, I found my answer. You double-click the auto-generated first argument (operate: (Double, Double) -> Double). :+1:

Awesome stuff, loving this course. But I gotta admit, these closures are still pretty confusing to me. I just haven’t grasped where and how you would use something like this…