What do the double arrows indicate in the return type of the last function here?
Are they used to indicate two different return values?
If so, how do you know which order the arrows are in, if the functions in chooseStepFunction()
were different types? E.g., if stepForward()
returned a String
func stepForward(input: Int) -> Int{
return input + 1
}
func stepBackward(input: Int) -> Int{
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int{
return backwards ? stepBackward: stepForward
}
Incredibly swiftly or speedily. The karate expert had the would-be mugger unconscious on the ground as swift as an arrow. Swift as an arrow, Mary finished her exam and raced out of the classroom. The shoppers ran through the mall as swift as arrows in search of great deals.
All of this information is rolled up into the function's definition, which is prefixed with the func keyword. You indicate the function's return type with the return arrow -> (a hyphen followed by a right angle bracket), which is followed by the name of the type to return.
To pass function as parameter to another function in Swift, declare the parameter to receive a function with specific parameters and return type. The syntax to declare the parameter that can accept a function is same as that of declaring a variable to store a function.
Every function has a function name, which describes the task that the function performs. To use a function, you "call" that function with its name and pass input values (known as arguments) that match the types of the function's parameters. Function parameters are also called as 'tuples'.
Given:
(x) -> (y) -> z
You would read this as:
A function which accepts
x
and returns a function which acceptsy
and returnsz
.
So in this case, chooseStepFunction
is a function that takes a bool and returns a function that takes an int and returns an int. This is right-associative, so you would read it as:
(backwards: Bool) -> ((Int) -> Int)
It's easiest to read this if you remember that the first set of parentheses (around Bool
) aren't particularly special. They're just like the second set (around Int
). (The parentheses aren't actually needed. (Int) -> Int
is the same as Int -> Int
.)
Realizing this will help when you encounter currying:
func addTwoNumbers(a: Int)(b: Int) -> Int
This is really the same as:
(a: Int) -> (b: Int) -> Int
A function that takes an int and returns a function that takes an int and returns an int.
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