Swift协议符合异步重载

huangapple go评论61阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月29日 22:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定