Given a function signature:
func myFunc(someClosure: (argA: TypeA!, argB: TypeB!) -> Void)
sometimes I don't need the passed parameters to the closure so the call is:
myFunc { (_,_) in
//bla bla
}
is there a way to skip this redundant (_,_) in
part?
An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.
In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World . Before you learn about closures, make sure to know about Swift Functions.
If we wanted to pass that closure into a function so it can be run inside that function, we would specify the parameter type as () -> Void . That means “accepts no parameters, and returns Void ” – Swift's way of saying “nothing”.
There is no way to skip it entirely, but if you won't use either argument, you can use
myFunc { _ in
// do stuff
}
Similarly, if you only need one of the arguments, you can use
myFunc { _, something in
// do stuff
}
Personally I don't like turning parameters into ( _ )
, so I use ( _ paramName )
(Swift 3, Xcode 8.3 beta)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With