Search code examples
swiftfunctionreturn

Swift - Function Types as Return Types


I'm trying to wrap my head around "Functions Types as Return Types (Swift Doc)". I noticed that there's also a similar post to this question but i'm still a bit confused.

I'm quite confused with the -> (Int) -> Int in chooseStepFunction. I see that chooseStepFunction is returning a function that returns an Int but i don't understand what that exactly means and why is the Int in () (Int). Also, how would re read this '-> (Int) -> Int

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
}

var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function

Solution

  • To make it clearer let's create a type alias

    typealias functionWithIntParameterAndIntReturnValue = (Int) -> Int
    

    and change chooseStepFunction to

    func chooseStepFunction(backwards:Bool) -> functionWithIntParameterAndIntReturnValue {
        return backwards ? stepBackward : stepForward
    }
    

    This matches exactly the signatures of both step... functions

    (input: Int) -> Int
    

    which have an Int parameter and return an Int. If you omit the parameter label you get

    (Int) -> Int
    

    The parentheses are a semantical requirement