如何修复涉及Protocol与类型别名的Swift循环引用编译错误?
修复Swift循环引用与虚假协议一致性错误
问题代码与报错
以下代码在Xcode 14.1中无法编译:
enum GenericState<Mode>: Hashable where Mode: Hashable {} // 错误:循环引用 protocol P { associatedtype Mode: Hashable // (虚假错误)- Type 'Self.Mode' does not conform to protocol 'Hashable' typealias SomeState = GenericState<Mode> typealias Foo = [CustomKeyPath<Self, String>] } struct Interface<Base> where Base: P {} typealias CustomKeyPath<Base, T> = KeyPath<Interface<Base>, T> where Base: P
触发的编译错误:
- 协议
P内部存在循环引用 - 针对
SomeState的虚假报错:编译器错误提示Self.Mode不符合Hashable协议,但实际上associatedtype Mode已经被约束为Hashable
修复方案
1. 打破循环引用
原代码中CustomKeyPath的where子句约束与协议P的Foo类型别名形成循环依赖。将Base: P的约束直接整合到CustomKeyPath的泛型参数定义中,替代原有的where子句即可解决:
typealias CustomKeyPath<Base: P, T> = KeyPath<Interface<Base>, T>
2. 消除虚假协议一致性错误
尽管associatedtype Mode已经声明了Hashable约束,但编译器未正确识别。在SomeState的类型别名中显式添加约束,即可让编译器正确解析:
typealias SomeState = GenericState<Mode> where Mode: Hashable
修复后的完整代码
enum GenericState<Mode>: Hashable where Mode: Hashable {} protocol P { associatedtype Mode: Hashable typealias SomeState = GenericState<Mode> where Mode: Hashable typealias Foo = [CustomKeyPath<Self, String>] } struct Interface<Base> where Base: P {} typealias CustomKeyPath<Base: P, T> = KeyPath<Interface<Base>, T>
内容的提问来源于stack exchange,提问作者Awais Fayyaz
相关产品推荐
相关产品推荐

