我有以下两个函数(编译时不会出错):
func hasLocalChanges() -> Bool {
return false
}
func hasRemoteChanges() async -> Bool {
return await Task{ true }.value
}
现在,假设我想引入第三个函数,如下所示:
func hasChanges() async -> Bool {
return self.hasLocalChanges() || await self.hasRemoteChanges()
}
然后,此函数将给我一个编译器错误,说明:
'async' call in an autoclosure that does not support concurrency
但为什么呢?
我可以通过交换操作数来解决此错误…
func hasChanges() async -> Bool {
return await self.hasRemoteChanges() || self.hasLocalChanges()
}
,这将再次使代码编译无误.
但我真的想利用延迟求值,最后执行异步函数.因此,实现这一目标的唯一方法是说…
func hasChanges() async -> Bool {
if !self.hasLocalChanges() {
return await self.hasRemoteChanges()
} else {
return true
}
}
…这似乎有点麻烦.
有谁能解释一下为什么我一开始就犯了这个错误?
EDIT:
非常感谢@aciniglio:
重写代码的一种方法如下(假设这两个函数也允许抛出):
func hasChanges() async throws -> Bool {
return try await hasLocalChanges().or(await hasRemoteChanges())
}
extension Bool {
func or(_ other: @autoclosure () async throws -> Bool) async rethrows -> Bool {
return self ? true : try await other()
}
}