Daniel Lyons
Daniel Lyons

Reputation: 129

Implicit parameters in trailing closure

I'm somewhat new to Swift. Not a total beginner.

Is there a way to pass a closure as a parameter without explicitly filling out that closure's parameter list?

Trying this code from here:

func addition(num1: Double, num2: Double) -> Double {
    return num1 + num2
}
func multiply(num1: Double, num2: Double) -> Double {
    return num1 * num2
}
func doMathOperation(operation:( _ x:Double, _ y:Double) -> Double, num1: Double, num2: Double) -> Double {
    return operation(num1, num2)
}
doMathOperation(operation: multiply, num1: 4, num2: 5) //20
doMathOperation(operation: addition, num1: 4, num2: 5) //9

So I thought I'd rewrite it to make it easier to read:

func addition (_ num1: Double, _ num2: Double)->Double {
    return num1 + num2
}
func multiply (_ num1: Double, _ num2: Double)->Double {
    return num1 * num2
}
func doMathOperation(_ num1: Double, _ num2: Double, operation: (_ x:Double,_ y:Double)->Double) ->Double {
    return operation(num1, num2)
}

Interestingly, this works:

doMathOperation(4, 5, operation: multiply) //20

But this doesn't:


doMathOperation(4, 5) {multiply} //error: contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored

As far as I know, they should mean the exact same thing, but when I use trailing closure syntax, the compiler won't let me compile it.

Upvotes: 1

Views: 830

Answers (1)

matt
matt

Reputation: 535202

In

doMathOperation(4, 5, operation: multiply)

...you are being asked for a function that takes two Double parameters, and multiply is the name of just such a function, so it compiles and works.

In

doMathOperation(4, 5) { ... }

the curly braces themselves are the (body of the) function that takes two Double parameters. It makes no sense to put the name of another such function inside the curly braces.

But of course you are free to call any function you like, passing along the parameters that were passed to you; hence this works:

doMathOperation(4, 5) { multiply($0,$1) }

So, just to sum up: In the first one

doMathOperation(4, 5, operation: multiply)

there is one function, multiply, and 4 and 5 are passed to it. In the second one

doMathOperation(4, 5) { multiply($0,$1) }

there are two functions, "anonymous" (the curly braces) and multiply, and the 4 and 5 are passed into the first one and then it calls the second one.

Upvotes: 4

Related Questions