在Swift中传递空闭包的优雅方式

dim*_*roc 22 cocoa-touch ios swift

在Swift中,我经常必须将noop闭包传递给方法,以符合方法的预期参数(arity).在Obj C的旧时代,人们可以通过nil一个noop回调并完成它.在没有像下面那样传递空块的情况下,在Swift中有更快更优雅的方法吗?

UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in }) // do nothing in callback

完整的例子:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

rob*_*off 42

一般来说,如果你不能通过nil:

var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,
    handler:{ _ in })
Run Code Online (Sandbox Code Playgroud)

您也可以传递nil这种情况,因为(从iOS 9.0开始)处理程序是Optional:

var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,
    handler:nil)
Run Code Online (Sandbox Code Playgroud)

  • `handler`的类型是`((UIAlertAction!) - > Void)!`,这意味着它是一个Implicitly Unwrapped Optional.这就是你可以为这个参数传递`nil`的原因.它有记录(有关详细信息,请参阅我的回答). (2认同)

Les*_*win 6

您可以定义一个noop用作默认闭包,它不执行任何操作:(参考:https://realm.io/news/closures-api-design)

func noop() {}

func noop<T>(value: T) {}

func noop<T>() -> T? { return nil }

func noop<T, S>(value: T) -> S? { return nil }
Run Code Online (Sandbox Code Playgroud)

使用:

var okAction = UIAlertAction(title: "Ok", 
                             style: UIAlertActionStyle.Default, 
                           handler: noop)
Run Code Online (Sandbox Code Playgroud)


Ima*_*tit 5

根据Xcode文档,UIAlertAction有一个convenience init方法具有以下声明:

convenience init(title: String, style: UIAlertActionStyle, handler: ((UIAlertAction!) -> Void)!) 
Run Code Online (Sandbox Code Playgroud)

如您所见,该handler参数是Implicitly Unwrapped可选的类型((UIAlertAction!) -> Void)!.所以你可以通过nil它.例如,您可以创建一个UIAlertController包含一个实例UIAlertActionhandler: nil:

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

因此,您不需要为其创建空块handler.