swift - 为什么我会遇到此一致性问题?
问题描述
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
in 协议来解决它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
}
解决方案
如果您按照以下方式考虑该错误,则该错误是有道理的。
/// 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 论坛可能是讨论这个问题的更好地方。
推荐阅读
- typescript - 如何根据联合类型的接口属性确定函数的参数行为?
- java - 如何在 Android 中停止铃声警报?
- fortran - 使用 gfortran 和 ifort 编译
- c# - 如何从 dll 中反编译/提取(cshtml--(剃刀视图))
- pandas - 如何从具有同一行值的两个字典创建数据框?
- python - Keras FFT层没有效果
- git - GH001:检测到大文件。您可能想尝试 Git 大文件存储
- bootstrap-4 - Bootstrap 4 - 我如何正确证明页脚中的某些内容?
- c++ - 涉及全局对象的循环依赖 C++
- maven - 如何假设从 maven Central 复制的 repo 的 bintray 所有权