加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:59:41 所属栏目:百科 来源:网络整理
导读:考虑以下: 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" }}
考虑以下:

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 = 10
fbc.hello() // 10
fbc.hi()    // 10

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读