我的 Swift 代码块之一是警报弹出窗口:
func alertNewBillCreated() {
let alert = UIAlertController(title: "Success", message: "Bill created and ready to be paid", preferredStyle: UIAlertControllerStyle.Alert)
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (UIAlertAction) in
self.navigationController?.popViewControllerAnimated(true)
}
alert.addAction(actionOK)
self.presentViewController(alert, animated: true, completion: nil)
}
像这样阅读其他 SO 帖子:Writing handler for UIAlertAction
他们都给出了包含处理程序部分并明确定义的示例,例如:
UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: {(alert: UIAlertAction!) in println("Foo")
但是,在我使用 Xcode 的自动完成功能帮助我编写警报 block 的上述代码中,我的版本在 handler
键后没有逗号。
这两个变体也有效(除了我上面的第一段代码):
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) in
...
})
和
let actionOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) in
...
})
这个奇怪的 Swift 语法异常规则是什么?
这不是一个错误吗?
我们不是用逗号分隔函数参数吗?
在我看来,我正在调用一个函数 UIAlertAction()
并且只向它传递两个参数 - title
和 style
因为那里只有 2 个逗号:
UIAlertAction(__ , __ ) { ... }
或者……这是……Ruby block 的 Swift 等价物? ( Best explanation of Ruby blocks? )
我的警报代码有效,没有损坏,以防有人好奇。
似乎与这么多规则和奇怪的语法不一致,使得记住 Swift 语法规则和学习 Swift 变得困难/困难。
希望 Swift 4.0 能够解决所有这些问题......
也许我提示太多了:D
最佳答案
如果最后一个参数是一个 block ,它可以像方法体一样附加。
阅读更多。
关于ios - Swift 警报处理程序语法奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39290843/