gpt4 book ai didi

swift - 构建 WatchOS 应用程序 : Develop and Design

转载 作者:行者123 更新时间:2023-11-30 13:05:19 25 4
gpt4 key购买 nike

我正在尝试运行《Build WatchOS:开发和设计》一书中的一些示例代码。以下代码段返回两个错误:

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

动画是这里有趣的部分。

() -> Void

表示animations采用一个函数,该函数必须不包含任何参数,并且返回Void

在你的情况下,你可以这样调用它:

animateWithDuration(0.2, animations: updateButtonToStopped())

但是...当您使用 updateButtonToStopped() 时,您实际上所说的是,“调用 updateButtonToStopped() 并使用输出 animations 参数”。这不是编译器所期望的,正如我们刚刚看到的,它期望的是一个不带参数并返回 Void 的函数。

所以当你说:

animateWithDuration(0.2, animations: updateButtonToStopped)

如果没有括号,则意味着您不调用 updateButtonToStopped,只需将其作为参数传递给 animate

希望这对您有帮助。

关于swift - 构建 WatchOS 应用程序 : Develop and Design,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39456721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com