ios - Swift 警报处理程序语法奇怪

标签 ios swift uialertaction

我的 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() 并且只向它传递两个参数 - titlestyle 因为那里只有 2 个逗号:

UIAlertAction(__ , __ ) { ... }

或者……这是……Ruby block 的 Swift 等价物? ( Best explanation of Ruby blocks? )

我的警报代码有效,没有损坏,以防有人好奇。

似乎与这么多规则和奇怪的语法不一致,使得记住 Swift 语法规则和学习 Swift 变得困难/困难。

希望 Swift 4.0 能够解决所有这些问题......

也许我提示太多了:D

最佳答案

关于ios - Swift 警报处理程序语法奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39290843/

相关文章:

ios - 将 UIAlertAction 标题向左对齐

ios - NSFetchedResultsController 试图限制显示的记录数

iOS 11/12 : How to fetch list of “People Album” from Photos. 应用程序

ios - 无法打开 Optional.Swift 中的 None 错误

swift - 在 Swift 中获取 UIAlertAction 的处理程序

ios - 快速单击按钮时出错

ios - 使用 NSURLRequest 发布到 Google Forms 表单

ios - presentViewController 黑色背景而不是透明

android - 是否可以在快速 blox 聊天中发送音频文件和 doc/pdf 文件

ios - 如何根据其内在内容调整 View 大小?