Search code examples
iosswiftcocoa-touch

Elegant way to pass empty closures in Swift


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
    }
}

Solution

  • In this case, you can pass nil, because the handler is an Optional:

    var okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
    

    The general way, if you can't pass nil:

    var okAction = UIAlertAction(title: "Ok", style: .default, handler: { _ in })