jfboisvieux
jfboisvieux

Reputation: 157

swift function () -> (Int) -> String

given the following function:

func returnFunc() -> (Int) -> String {
    func innerFunc(i: Int) -> String {
        return " value returned : \(i)"
    }
    return innerFunc
}

returnFunc()    // (Int) -> String -- (correct)
returnFunc()(5) // 'value returned: 5'

why do I need to provide () followed by (5) to get this result ?

I need to understand how the 5 value is given to the argument "i" of innerFunc

I'll really appreciate any pointer which explains this feature.

Upvotes: 0

Views: 655

Answers (3)

Chris
Chris

Reputation: 4391

This is because returnFunc() instantiates a new instance of a function that takes an integer and returns a string.

returnFunc()(5) also calls the function and passes 5 as the argument to this returned function, due to the way they are chained together.

It’s a little bit like if a function returned an array, you would access an array element with:

func returnArray() -> [Int] {
    return [0, 1, 2, 3, 4]
}

returnArray()[2] // This evaluates to 2

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54716

returnFunc is a curried function, whose type can be also written as func returnFunc() -> ((Int) -> String), since it is actually a function that takes no input arguments and returns another function that takes a single input argument of type Int and returns a String.

So by calling returnFunc(), you simply return a function, namely innerFunc, but you need to pass an input argument to innerFunc to be able to execute it. This is done by the (5) at the end of returnFunc()(5).

It becomes more clear if you write it out in steps:

let innerFunc = returnFunc()
let fiveString = innerFunc(5) // "value returned: 5"

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

Because the return of returnFunc is a function which means

returnFunc() = innerFunc 

so this

returnFunc()(5)

means

innerFunc(5)

Upvotes: 1

Related Questions