In Swift, I often have to pass a noop closure to a method just to comply with the method's expected parameters (arity). In the good old days of Obj C, one could pass nil
for a noop callback and be done with it. Is there a quicker more elegant way to do that in Swift without passing an empty block like below?
UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in }) // do nothing in callback
Complete example:
import UIKit class UIAlertControllerFactory { class func ok(title: String, message: String) -> UIAlertController { var alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in }) alertController.addAction(okAction) return alertController } }
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.
Swift Closure Declaration Here, parameters - any value passed to closure. returnType - specifies the type of value returned by the closure. in (optional) - used to separate parameters/returnType from closure body.
Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you. Don't worry if you aren't familiar with the concept of capturing.
How A Closure Works In Swift. Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable. You can then pass it around in your code, for instance to another function.
The general way, if you can't pass nil
:
var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ _ in })
You can also pass nil
in this case, because (as of iOS 9.0) the handler is an Optional
:
var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil)
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