protocol A {}
protocol B: A {}
protocol C {
var X: A { get }
}
struct D: C {
let X: B // ERROR: does not conform to protocol "C"
}
这应该没问题,因为 B
符合 A
吗?
我试图通过在协议 associatedtype
中使用 C
来补救它:
protocol A {}
protocol B: A {}
protocol C {
associatedtype SomeType: A
var X: SomeType { get }
}
struct D: C {
let X: B // ERROR: does not conform to protocol C -- seemingly requiring a concrete type
}
答案 0 :(得分:-1)
如果你按照以下方式思考这个错误是有道理的。
/// It does not have any requirements
protocol A {}
/// It has to satisfy all of the requirements of A (whatever they are)
/// It does not have any of it's own requirements (currently)
/// It is expected to add some additional requirements of it's own
/// Otherwise it defeats the purpose of having this
protocol B: A {}
/// This has only one requirement, X that conforms to A
protocol C {
var X: A { get }
}
/// This has only one requirement, X that conforms to B
/// The problem here is
/// - A & B are different and can not be used interchangeably
/// (at least in the current versions)
struct D: C {
let X: B // ERROR: does not conform to protocol "C"
}
从逻辑上讲这是有道理的 - B
必须满足 A
的所有要求,因此应该被允许。
我认为 Swift Forums 可能是讨论这个更好的地方。