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

时间:2015-11-28 05:35:54

标签: swift swift2 associated-types protocol-extension

请考虑以下事项:

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"
  }
}

此代码编译。但是如果我注释掉关联类型typealias A = String的明确定义,那么由于某种原因,swiftc无法推断出类型。

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

我不确定这是否是该语言的错误/不成熟,或者我错过了协议扩展中的一些细微差别,这正确地导致了这种行为。< / p>

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

2 个答案:

答案 0 :(得分:1)

看一下这个例子

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"
    }
}

with generics

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

答案 1 :(得分:0)

为了符合所述协议,需要为协议中的关联类型提供显式值。这可以通过硬编码类型来完成,就像您使用typealias A = String完成的那样,或使用您提到的参数化类型,如下所示:

class FooBarClass<T>: FooBar {
    typealias A = T
    ...
}

Swift不会从协议的实现方法推断出您的关联类型,因为多种方法可能存在歧义,类型不匹配。这就是必须在实现类中明确解析typealias的原因。

相关问题