Swift协议扩展实现具有共享关联类型的另一协议

Swift协议扩展实现具有共享关联类型的另一协议,第1张

概述考虑以下: protocol Foo { typealias A func hello() -> A}protocol FooBar: Foo { func hi() -> A}extension FooBar { func hello() -> A { return hi() }}class FooBarClass: FooBar { typeali 考虑以下:

protocol Foo {  typealias A  func hello() -> A}protocol Foobar: Foo {  func hi() -> A}extension Foobar {  func hello() -> A {    return hi()  }}class FoobarClass: Foobar {  typealias A = String  func hi() -> String {    return "hello world"  }}

这段代码编译.但是如果我注释掉关联类型类型A = String的显式定义,那么由于某种原因,swiftc无法推断出类型.

我感觉这与两个共享相同关联类型但没有直接断言的协议有关,例如,类型参数化(可能关联类型不够强大/不够成熟?),这使得类型推断模糊不清.

我不确定这是否是该语言的错误/不成熟,或者可能,我错过了协议扩展中的一些细微差别,这恰恰导致了这种行为.

有人可以对此有所了解吗?

解决方法 看看这个例子

protocol Foo {    typealias A    func hello() -> A}protocol Foobar: Foo {    typealias B    func hi() -> B}extension Foobar {    func hello() -> B {        return hi()    }}class FoobarClass: Foobar {    //typealias A = String    func hi() -> String {        return "hello world"    }}

与泛型

class FoobarClass<T>: Foobar {    var t: T?    func hi() -> T? {        return t    }}let fbc: FoobarClass<Int> = FoobarClass()fbc.t = 10fbc.hello() // 10fbc.hi()    // 10
总结

以上是内存溢出为你收集整理的Swift协议扩展实现具有共享关联类型的另一协议全部内容,希望文章能够帮你解决Swift协议扩展实现具有共享关联类型的另一协议所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1017753.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存