Reputation: 1665
You can drop the code below into playgrounds.
import UIKit
class MyClass {
func foo(a: String, b: () -> ()) {
b()
}
func bar(a: String = "a", b: () -> ()) {
b()
}
}
let object = MyClass()
object.foo("x") { () -> () in
println("foo")
}
object.bar() { () -> () in
println("foo")
}
object.bar()
call produces Missing argument for parameter 'b' in call
The question is: am I doing something wrong, or trailing closures are not supported in methods with default parameter values?
Upvotes: 2
Views: 653
Reputation: 72760
It does look like a problem with trailing closures - this code works:
object.bar(b: { () -> () in
println("foo")
})
However if the external name is removed:
func bar(a: String = "a", _ b: () -> ()) {
b()
}
this no longer works:
object.bar({ () -> () in
println("foo")
})
Moreover using a function having a string as the 2nd parameter:
func test( val1: String = "a", val2: String) {
}
the default parameter is correctly assigned, so this succeeds:
test("me")
which is a different behavior than using closures.
Conclusion: a method or function with parameter(s) having default value and a trailing closure does not work if at least one of the parameters with default value is not specified. Avoiding the trailing closure the function works only if the parameter has external name.
Upvotes: 2