user1107173
user1107173

Reputation: 10784

Swift: Closure with Known Types Syntax

I am trying to understand the syntax behind Known Types Closures.

Below is an example:

func applyMutliplication(value: Int, multiFunction: Int -> Int) -> Int {
    return multiFunction(value)
}

applyMutliplication(2, multiFunction: {value in
    value * 3  // returns a 6
})

I am struggling with multiFucntion: Int -> Int. Is this the same as (multiFunction: Int) -> Int?

When I try I try the following signature in playground, I get an error:

//below gives an error
func applyMutliplication(value: Int, ((multiFunction: Int) -> Int)) -> Int {
    return multiFunction(value)
}

My understanding is: applyMultiplication takes in an Int called value, and a closure called multiFunction that takes an Int and returns an Int. applyMultiplication also returns Int

But then I am confused with as to how does {value in value * 3} causes it to return a 6?

Upvotes: 0

Views: 43

Answers (1)

Sulthan
Sulthan

Reputation: 130172

multiFucntion: Int -> Int. is not (multiFunction: Int) -> Int?

multiFunction is a function parameter name, it does not have anything to do with the type. The type is just (Int) -> Int. A function that has one Int parameter and returns an Int.

You are passing a closure that returns its parameter multiplied by 3 and you are passing it 2 as its parameter. The result is logically 6.

Maybe it could be more readable this way:

func applyMutliplication(value: Int, multiFunction: Int -> Int) -> Int {
    return multiFunction(value)
}

let multiplyByThree: (Int) -> Int = {value in
    value * 3  // returns a 6
}

applyMutliplication(2, multiFunction: multiplyByThree)

Upvotes: 3

Related Questions