Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the two arrows in the user defined chooseStepFunction() in Swift?

Tags:

function

swift

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
}
like image 931
MichaelGofron Avatar asked Jun 09 '14 18:06

MichaelGofron


People also ask

What does arrow mean in Swift?

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.

How to specify return type in Swift?

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.

How to pass arguments in Swift?

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.

How to call function in function Swift?

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'.


Video Answer


1 Answers

Given:

(x) -> (y) -> z

You would read this as:

A function which accepts x and returns a function which accepts y and returns z.

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.

like image 178
Rob Napier Avatar answered Nov 15 '22 15:11

Rob Napier