What it the most common situation where you would want to return a function from a function in Swift?
In the code below I'm returning a function but I don't really see the purpose since the function I'm returning is inside the function who is returning it. The reason I'm confused is because we could accomplish the same thing with just one function.
func person () -> ((String, Int) -> String) {
func info(name: String, age: Int) -> (String) {
return "\(name) is \(age) old"
}
return info
}
let nathan = person()
nathan("Nathan", 3)
print(nathan("Nathan", 3))
Can someone point out common situations where you would want to return a function and probably illustrate it with a better example?
I want to understand this since this is fundamental for programming in general not just Swift (I think).
A classic example would be in a calculator program, e.g.:
func operatorForString(str: String) -> ((Float, Float) -> Float)? {
if str == "+" {
return (+) // brackets required to clarify that we mean the function
} else if str == "-" {
return (-)
} else if str == "*" {
return (*)
} else if str == "/" {
return (/)
} else if str == "**" {
return pow // No brackets required here
} else {
return nil
}
}
if let op = operatorForString("-") {
let result = op(1, 2) // -1
}
It's rather contrived, but it illustrates the principle simply...
As an "exercise to the reader" try to do it as a Dictionary
lookup, rather than repeated if
s :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With