Reputation: 16758
I know it is possible to define methods which accept closures like this:
A. Single closure as input parameter
func testOfClosures (flag: Int, closure1: () -> ())
{
closure1()
}
B. Multiple closures as input parameters
func testOfClosures (flag: Int, closure1: () -> (), closure2: () -> (), closure3: () -> ())
{
switch flag
{
case 1:
closure1()
case 2:
closure2()
default:
closure3()
}
}
Interestingly in first case we can invoke it like this:
testOfClosures(1){
println("print closure 1")
}
but in second case, we cannot invoke it like this:
testOfClosures(1,{
println("print closure 1")
},
{
println("print closure 2")
})
{
println("print closure 3")
}
and we have to invoke it like this:
testOfClosures(1,{
println("print closure 1")
},
{
println("print closure 2")
},
{
println("print closure 3")
})
Any reasons?
Upvotes: 5
Views: 4622
Reputation: 8328
Yes you can do it since Swift 5.3.
Please see this example
// Multiple trailing closure arguments
UIView.animate(withDuration: 0.3) {
self.view.alpha = 0
} completion: { _ in
self.view.removeFromSuperview()
}
Credit and more infos from this Proposal
Upvotes: 6
Reputation: 6493
It looks like the trailing closure syntax is very specific about the position of the opening {
and requires it to be on the same line as the closing )
The below works
testOfClosures(1,{
println("print closure 1")
},
{
println("print closure 2")
}) {
println("print closure 3")
}
As far as multiple trailing closures, that is not possible. The documentation specifically states only the final closure as using the special syntax.
Upvotes: 4