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协议扩展实现具有共享关联类型的另一协议所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)