首页 > 解决方案 > 为什么我会遇到此一致性问题?

问题描述

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吗?

我试图通过使用associatedtypein 协议来解决它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
}

标签: swift

解决方案


如果您按照以下方式考虑该错误,则该错误是有道理的。

/// 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 论坛可能是讨论这个问题的更好地方。


推荐阅读