嵌套闭包不喜欢参数列表

Ilk*_*aci 11 closures uiview uianimation completionhandler swift

UIView需要根据自定义控件的完成处理程序更改警告标签:

    voucherInputView.completionHandler = {[weak self] (success: Bool) -> Void in

        self?.proceedButton.enabled = success
        self?.warningLabel.alpha = 1.0

        if success
        {
            self?.warningLabel.text = "Code you entered is correct"
            self?.warningLabel.backgroundColor = UIColor.greenColor()
        }
        else
        {
            self?.warningLabel.text = "Code you entered is incorrect"
            self?.warningLabel.backgroundColor = UIColor.orangeColor()
        }


        UIView.animateWithDuration(NSTimeInterval(1.0), animations:{ ()-> Void in
            self?.warningLabel.alpha = 1.0
        })
Run Code Online (Sandbox Code Playgroud)

最终动画块在表单中显示错误.

Cannot invoke 'animateWithDuration' with an argument list of type '(NSTimeInterval), animations: ()-> Void)'
Run Code Online (Sandbox Code Playgroud)

如果我在完成闭包之外的某个地方调用它就可以了.

Ant*_*nio 39

问题是闭包是隐式返回此表达式的结果:

self?.warningLabel.alpha = 1.0
Run Code Online (Sandbox Code Playgroud)

但封闭本身被宣布为返回Void.

添加显式return应解决问题:

UIView.animateWithDuration(NSTimeInterval(1.0), animations: { ()-> Void in
    self?.warningLabel.alpha = 1.0
    return
})
Run Code Online (Sandbox Code Playgroud)

  • 这为我修好了,但有人会介意解释*为什么*这种行为对很多人来说是如此奇怪和意外?顺便说一句,在你的例子中你可以用`_`替换`() - > Void`并使用`追加return; 返回到同一行.还有,你可以写`; ()`而不是单行`return`.:) (5认同)