2

Regarding the code below, I was wondering how nested functions such as stepForward, stepBackward, when they are actually called through 'moveNearerToZero(currentValue), take currentValue as their arguments.

According to the definition of the function chooseStepFunction, the return type is (Int) -> Int. Then, is it because of the parenthesis around Int that the nested functions are able to take currentValue as their arguments?

I can't undesrtand how the value of -4 of currentValue is captured in two nested functions.

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)

while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
1
  • It isn’t captured. It is passed directly: currentValue = moveNearerToZero(currentValue). Commented Jun 10, 2020 at 12:53

2 Answers 2

3

Functions in Swift are first class citizens. This means that functions can be passed around or stored like a variable, just like any other swift type.

Anything that follows the first -> is the type being returned by that method. In this case chooseStepFunction returns another method that takes one parameter (Int) and returns one value (Int). The parenthesis around the first Int, mean that it's an input parameter.

With that in mind, moveNearerToZero is function that takes one Int and returns another Int. To call that method, you then simply do moveNearerToZero(1) and so on.

I highly recommend you read Apple's section on functions to better understand how functions can be used or passed around. https://docs.swift.org/swift-book/LanguageGuide/Functions.html

Sign up to request clarification or add additional context in comments.

Comments

0

chooseStepFunction(backward: currentValue > 0) returns "stepForward" function. In "stepForward" function as the value is incremental by 1. So, first -4 is getting printed than -3(-4+1) is getting printed and so on until currentValue reaches 0 where the while loop terminates.

2 Comments

it doesn't return a reference, but the actual method.
Yes. I mean to say the reference of the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.