Swift中的'finish in'是什么意思?

3

我是一个初学者,一直在通过苹果的Playgrounds和随机的图书教程进行学习。我正在学习一个关于闭包的教程。我在另一个教程中看到过'finish in'这个术语,但我不知道它在通俗易懂的术语中确切地是什么意思。

它完成了什么,正在完成什么,在什么内部完成?还是有一种操作顺序的想法?

这是使用它的函数:

func playSequence(index: Int, highlightTime: Double){
        currentPlayer = .Computer

        if index == inputs.count{
            currentPlayer = .Human
            return
        }

        var button: UIButton = buttonByColor(color: inputs[index])
        var originalColor: UIColor? = button.backgroundColor
        var highlightColor: UIColor = UIColor.white

        UIView.animate(withDuration: highlightTime, delay: 0.0, options: [.curveLinear, .allowUserInteraction, .beginFromCurrentState], animations: {
            button.backgroundColor = highlightColor
        }, completion: {
            finished in button.backgroundColor = originalColor
            var newIndex: Int = index + 1
            self.playSequence(index: newIndex, highlightTime: highlightTime)
        })
    }

1
一切都是从上到下按顺序进行的。最后一部分是动画...按钮的backgroundColor设置为highlight颜色。当动画完成时(持续时间是方法的“highlightTime”参数),完成块中的代码将被执行。 - Adrian
@Adrian 这个问题特别涉及到 finished in 部分,而不是关于 UIView animate... 方法的一般性问题。 - rmaddy
1个回答

3

finished是传递给completion闭包的参数。而in则是Swift中闭包语法的一部分。

UIView animate方法的完整签名为:

class func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIViewAnimationOptions = [], animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)

注意,completion闭包的参数之一是Bool类型。而你代码中的finished就是该参数的名称。

文档中有这样一段描述completion参数的摘录:

此块没有返回值,并且需要一个布尔参数,指示动画在调用完成处理程序之前是否实际完成。

一个更典型的编写代码的方式是:

UIView.animate(withDuration: highlightTime, delay: 0.0, options: [.curveLinear, .allowUserInteraction, .beginFromCurrentState], animations: { 
    // animation code
}) { (finished) in
    // completion code
}

这种语法比你所使用的语法更加清晰易懂。这也是使用“尾随闭包”语法。

另一种更接近你的用法的方式是:

UIView.animate(withDuration: highlightTime, delay: 0.0, options: [.curveLinear, .allowUserInteraction, .beginFromCurrentState], animations: { 
    // animation code
}, completion: { (finished) in
    // completion code
})

你的用法只是省略了参数周围的括号,并且忽略了换行。将它们添加回去可以使代码更清晰。


谢谢,这也有所帮助。如果我想要理解单词"in"的作用,我应该搜索什么?还是这只是参数名? - Laurence Wingo
1
请阅读《The Swift Programming Language》书中的“Closures”章节。in仅是语法的一部分。 - rmaddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接