英文:
Swift protocol conformance with async overload
问题
为什么这段代码能够成功编译和运行?(Swift 5.8)
protocol AsyncOverloaded {
func load()
func load() async throws
}
class MyClass: AsyncOverloaded {
func load() {
print("load called")
}
}
let myClass = MyClass()
myClass.load()
// 输出 "load called"
据我理解,MyClass
实际上并没有遵循协议 AsyncOverloaded
。
英文:
Why does this successfully compile and run? (Swift 5.8)
protocol AsyncOverloaded {
func load()
func load() async throws
}
class MyClass: AsyncOverloaded {
func load() {
print("load called")
}
}
let myClass = MyClass()
myClass.load()
// prints "load called"
To my understanding MyClass
does actually not conform to protocol AsyncOverloaded
.
Thanks in advance.
答案1
得分: 3
MyClass
中的 load()
函数同时满足协议要求。非抛出异常的函数可以满足需要抛出异常的函数的要求,因为它就像一个永远不会真正抛出异常的抛出异常函数一样。同样,同步函数可以满足 async
的要求。
英文:
The function load()
in MyClass
satisfies both protocol requirements.
A non throwing function satisfies a requirement for a throwing function since it's just like a throwing function that never actually throws. Similarly a synchronous function can satisfy an async
requirement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论