0

我的 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 帖子:为 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()并且只传递了两个参数 -title因为style只有 2 个逗号:

UIAlertAction(__ , __ ) { ... }

或者是......这...... Swift 相当于 Ruby 块?(Ruby 块的最佳解释?

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

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

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

也许我抱怨太多了:D

4

1 回答 1

1

如果最后一个参数是一个块,它可以像方法体一样附加。

阅读更多。

https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94 尾随闭包

于 2016-09-02T11:11:49.257 回答