user1107173 - 6 months ago 15

Swift Question

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`

`(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`

`Int`

`value`

`multiFunction`

`Int`

`Int`

`applyMultiplication`

`Int`

But then I am confused with as to how does

`{value in value * 3}`

`6`

Answer

`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)
```