ios - 'finish in' 在 Swift 中是什么意思?

标签 ios swift function closures

我是一个菜鸟,一直在从 Apple 的 Playgrounds 和随机书籍中学习教程。我正在编写一个处理闭包的教程。我之前在另一个教程中看到过这个“完成于”,但我不知道它在外行术语中的确切含义。

它正在完成什么,正在完成什么,里面有什么?还是有操作顺序的想法?

这是使用它的函数:

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)
        })
    }

最佳答案

finishedcompletion 闭包的参数。 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 参数的文档摘录指出:

This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called.

更典型的代码编写方式如下:

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
})

您的用法只是省略了参数周围的括号,并且省去了换行符。将这些重新添加进去可以使代码更清晰。

关于ios - 'finish in' 在 Swift 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250186/

相关文章:

ios - 调整 UIImage 大小以适应表格单元格 ImageView

javascript - 在 console.log 中立即出现奇怪的行为错误

c++ - 为什么函数的默认值为1?

javascript - 在 <script> 标签中声明一个 function() 是必要的吗?

ios - NSDateFormatter 将 rails 字符串转换为 NSDate 返回 nil?

ios - Phonegap 在构建期间不会将插件文件复制到 ios 平台目录

ios - 解析 Swift 登录错误 : Invalid User Credentials

swift - 模型 I/O – 如何使用 `makeVerticesUniqueAndReturnError()` 实例方法?

ios - 我可以在 iOS 后台获取中进行网络调用吗?

ios - iOS 是否会限制预定的本地推送通知?