我正在尝试从Build WatchOS:Develop and Design一书中运行一些示例代码。以下代码段返回两个错误:
watchDir
在对animateWithDuration()的调用中都会发生这两个错误,并指出存在类型冲突。关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
而不是像这样调用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
接受一个函数,该函数必须不包含任何参数,并返回Void
。
在你的情况下,你这样称呼它:
animateWithDuration(0.2, animations: updateButtonToStopped())
但是...当你使用updateButtonToStopped()
时,你实际上说的是,"调用updateButtonToStopped()
并使用的输出为{{ 1}}参数"。这不是编译器所期望的,正如我们刚才看到的那样,它期望一个函数,不带参数并返回animations
。
所以当你说:
Void
如果没有括号,则表示您不会调用animateWithDuration(0.2, animations: updateButtonToStopped)
,只需将其作为参数传递给updateButtonToStopped
。
希望这会对你有所帮助。