构建 WatchOS 应用程序:开发和设计

Build WatchOS Apps: Develop and Design

我正在尝试 运行 《构建 WatchOS:开发和设计》一书中的一些示例代码。下面这段代码returns两个错误:

@IBAction func buttonTapped(){
        if animating {
            spinnerImage.stopAnimating()
            animating = false
            animateWithDuration(0.2, animations: updateButtonToStopped())
        } else {
            spinnerImage.startAnimating()
            animating = true
            animateWithDuration(0.2, animations: updateButtonToGoing())
        }

    }

这两个错误都发生在对 animateWithDuration() 的调用中,表明存在类型冲突。关于如何解决此问题的任何想法?

赶时间?

而不是像这样调用 animateWithDuration

animateWithDuration(0.2, animations: updateButtonToStopped())

你想给它你的 updateButtonToStopped 函数作为参数,如下所示:

animateWithDuration(0.2, animations: updateButtonToStopped)

注意 updateButtonToStopped 后面的 () 不见了。

当然 updateButtonToGoing 也是如此 :)

为什么?

如果您查看 animateWithDuration 的文档(您可以看到 here 的 Swift 3 版本),您可以看到签名如下所示:

func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void)

animations 是这里有趣的部分。

() -> Void

表示 animations 接受一个函数,该函数必须不包含参数并且 returns Void.

在你的情况下,你可以这样称呼它:

animateWithDuration(0.2, animations: updateButtonToStopped())

但是...当您使用 updateButtonToStopped() 时,您实际上是在说 "call updateButtonToStopped() and use the output of that for the animations parameter"。这不是编译器所期望的,正如我们刚刚看到的,它期望的是一个函数,不带参数并返回 Void.

所以当你说:

animateWithDuration(0.2, animations: updateButtonToStopped)

没有括号意味着你不调用updateButtonToStopped,你只是将它作为参数传递给animate

希望对您有所帮助。