ios - Swift 函数参数默认值

标签 ios swift function parameters swift2

我正在创建一个包装函数,用于在 swift 中呈现警报 View 。

这是当前的工作代码,但目前我无法为 .presentViewController 函数中的“completion”参数传递函数

func showAlert(viewClass: UIViewController, title: String, message: String)
{
    // Just making things easy to read
    let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))

    // Notice the nil being passed to "completion", this is what I want to change
    viewClass.presentViewController(alertController, animated: true, completion: nil)
}

我希望能够将函数传递给 showAlert 并在完成时调用该函数,但我希望该参数是可选的,因此默认情况下它为 nil

// Not working, but this is the idea
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void?) = nil)
{
    let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))

    viewClass.presentViewController(alertController, animated: true, completion: action)
}

我得到以下信息,无法将类型“()”的值转换为预期参数类型“() -> Void?”

编辑

感谢 Rob,它现在可以按语法运行,但是当我尝试调用它时,我得到:

无法将类型“()”的值转换为预期的参数类型“(() -> Void)?”

这是我的称呼

showAlert(self, title: "Time", message: "10 Seconds", action: test())

test() {
    print("Hello")

}

最佳答案

您把问号放在了错误的位置。这有效:

// wrong: action: (() -> Void?) = nil
// right: action: (() -> Void)? = nil

func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void)? = nil)
{
    ...
}

调用时不要包含括号:

showAlert(self, title: "Time", message: "10 Seconds", action: test)

关于ios - Swift 函数参数默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443112/

相关文章:

ios - 使用 Kiwi 测试 JASidePanel

ios - 突然收到来自 CFNetwork/Darwin 的大量请求

javascript - JS 函数就这么简单,超链接语法

php - 如何将 $smarty 对象分配给 php 函数?

python - 没有 IN 运算符的列表如何值

android - Unity 的 OnApplicationPause 是否适用于 iOS/Android?

iOS 8 Swift 应用放大显示

ios - 了解 ARKit 中的 3D 对象变换属性

ios - 更改 iOS 导航栏的颜色

ios - 在 Cloud Code 中解析 LiveQuery