Swift 函数默认值

Swift 函数默认值

在 Swift 中,函数的内部参数标签不会用来区分函数,另外参数是可以指定默认值的。

如下函数:

var kRootViewController: UIViewController? { return UIApplication.shared.keyWindow?.rootViewController }

func alert(_ message: String, _ cancelHandler: ((UIAlertAction)->Void)? = nil, _ confirmHandler: ((UIAlertAction)->Void)? = nil) {
    let alert = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
    
    let cancelAction = UIAlertAction.init(title: "取消", style: .cancel, handler: cancelHandler)
    alert.addAction(cancelAction)
    
    let confirmAction = UIAlertAction.init(title: "确认", style: .destructive, handler: confirmHandler)
    alert.addAction(confirmAction)
    kRootViewController?.present(alert, animated: true, completion: nil)
    
}

作为一个全局函数,可以直接进行提示,也可以提供取消或确认操作。

但是如果只是想进行简单的提示,并提供下面的函数:

func alert(_ message: String) {
    let alert = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
    let cancelAction = UIAlertAction.init(title: "知道了", style: .cancel, handler: nil)
    alert.addAction(cancelAction)
    kRootViewController?.present(alert, animated: true, completion: nil)
}

这样编译过程是不会报错的,但是实际执行时,如果不指定取消操作或确认操作,则总是执行 alert(_:) 函数,即默认参数无效了,所以应当避免这种写法,可以取消第一函数的确认操作参数的默认值。

func alert(_ message: String, _ cancelHandler: ((UIAlertAction)->Void)? = nil, _ confirmHandler: ((UIAlertAction)->Void)?) {
	.
	.
	.
}

默认参数的使用可以使代码更加简洁且提高重用,如下函数,可以不传递第二个参数,调用时,就如同声明了两个函数一样。

func alertActionSheet(titles: [String], handler: ((UIAlertAction)->Void)? = nil) {
    let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
    for title in titles {
        let alertAction = UIAlertAction.init(title: title, style: .default, handler: handler)
        alert.addAction(alertAction)
    }
    
    let cancelAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
    alert.addAction(cancelAction)
    kRootViewController?.present(alert, animated: true, completion: nil)
}
发布了129 篇原创文章 · 获赞 23 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/u011374318/article/details/99900404
今日推荐