我对swift通用协议有一个奇怪的问题。这是我的示例代码:
protocol A {
var s: String? { get }
}
protocol B: A {
var d: Int? { get }
}
protocol Aed {
associatedtype T: A
var a: T! { get }
}
class AClass: Aed {
var a: B!
}
在线class AClass: Aed {
我收到错误type 'AClass' does not conform to protocol 'Aed'
。我不明白为什么swift无法推断a的类型,看起来很简单,不是吗?
答案 0 :(得分:1)
原因似乎与您无法做到的原因相同:
protocol A {
var s: String? { get }
}
protocol B: A {
var d: Int? { get }
}
class AClass<T: A> {
var a: T!
}
class BClass: AClass<B> {
}
这里swift给出错误using 'B' as a concrete type conforming to protocol 'A' is not supported
。 Swift不支持使用协议作为泛型约束的类型。您需要提供具体的实现。
答案 1 :(得分:0)
protocol A {
var s: String? { get }
}
protocol B: A {
var d: Int? { get }
}
protocol Aed {
associatedtype T: A
var a: T! { get }
}
class AClass<Element:B>: Aed {
typealias T = Element
var a: Element!
}
// usage
class MyElement: B {
var d: Int?
var s: String?
}
var myElement = MyElement()
myElement.d = 100
myElement.s = "hello"
var anInstance = AClass<MyElement>()
anInstance.a = myElement
print(anInstance.a.d ?? 0) // 100
print(anInstance.a.s ?? "") // hello