How does this function call this closure when each returns just a single Int?

How does this function call this closure when each returns just a single Int?

Problem Description:

I find this code very confusing:

let myClosure = { (number1: Int, number2: Int) -> Int in
    return number1 * number2
}

func useClosure(closure: (Int, Int) -> Int) {
    let result = closure(2, 3)
    print(result) // prints 6
}

useClosure(closure: myClosure)

The func useClosure takes 2 Ints with the parameter name closure which is the closure myClosure but myClosure has only 1 returned Int, so how can it be the parameter of useClosure?

And where is myClosure getting number1 and number2 from? From useClosure?

On the surface, it seems 2 and 3 are being passed to myClosure but it’s not clear how that is happening.

It all seems circular to me and makes little sense.

I haven’t really tried anything to "resolve" this as it doesn’t really need resolution. The code works fine. I’m just struggling to understand it – from where I am in my journey as a developer.

Solution – 1

If you look at the declaration of myClosure – or even better, option+click on it – you’ll see that its type is (Int, Int) -> Int. Which is exactly the type of the input argument useClosure expects.

That type signature represents a closure, which takes two Ints as input and returns an Int.

The func useClosure takes 2 Ints with the parameter name closure

useClosure takes a closure as its input, not a pair of Ints as you claim.

You are passing the values inside useClosure to the input argument, closure.

When looking at type signatures, everything on the left-hand side of -> represents the input arguments to the function, while everything on its right hand side represents the return type.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject