There is a func:
func (first: Int) -> Int -> Bool -> String {
return ?
}
How to write the return value? I'm so confused about the return type like of the func above.
Read from right to left when it comes into parsing function/closure returns. The right outermost one is the return type, and you can place the rest into parentheses.
Thus, your function declaration is equivalent to
func (first: Int) -> ((Int) -> ((Bool) -> String))
and to
func (first: Int)(_ second: Int)(_ third: Bool) -> String
though this form will no longer be supported in Swift 3.0 (thanks @Andrea for the heads up).
This is known as function currying. You function returns a function that takes an Int
as argument and returns another function that takes a Bool
as parameter and returns a String
. This way you can easily chain
function calls.
So the body of your method must return the first function in the list, one that has the following signature:
func ((Int) -> ((Bool) -> String))
You can then call it like this:
f(1)(2)(true)
let's say you define a closure
let closure: Int -> Bool
once the closure type is known (type of parameters and return type), writing it is quite easy, you name the list of parameters, followed by keyword in
and then the function's body (with a return at the end, if the function return type isn't Void
(a.k.a ()
)
// closure that returns if an integer is even
closure = { integer in
return integer %2 == 0
}
In your case, Int -> Int -> Bool -> String
means
A way to write that in code :
func prepareForSum(first: Int) -> Int -> Bool -> String {
return { secondInteger in
return { shouldSumIntegers in
var result: Int
// for the sake of example
// if boolean is true, we sum
if shouldSumIntegers {
result = first + secondInteger
} else {
// otherwise we take the max
result = max(first, secondInteger)
}
return String(result)
}
}
now you can use it like that
let sumSixteen = prepareForSum(16) // type of sumSixteen is Int -> Bool -> String
let result1 = sumSixteen(3)(true) // result1 == "19"
let result2 = sumSixteen(26)(false) // result2 == "26"
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