Swift警报处理程序语法奇怪

时间:2016-09-02 11:03:15

标签: 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的自动完成功能来帮助我编写警报块,我的版本没有跟随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,因为只有两个逗号:

UIAlertAction(__ , __ ) { ... }

或者......这...... Swift相当于Ruby块? (Best explanation of Ruby blocks?

我的警报代码有效,如果有人好奇的话,它没有被破坏。

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

希望通过Swift 4.0,所有这些都被解决了......

也许我抱怨太多了:D

1 个答案:

答案 0 :(得分:1)