SwiftUI以协议作为类型时出现无法符合Identifiable/Hashable报错如何解决
祝各位开发者假期愉快、新年快乐!
目前在实际开发中把协议作为通用类型使用,基础协议定义如下:
protocol Protocol_A_Or_B { } protocol ProtocolA: Protocol_A_Or_B, Identifiable, Hashable, CaseIterable { } protocol ProtocolB: Protocol_A_Or_B, Identifiable, Hashable, CaseIterable { }
为排除无关变量,已移除协议中所有自定义属性与方法。编写了两个分别遵循ProtocolA、ProtocolB的枚举,同时定义主枚举MainEnum_,该枚举提供一个计算属性,可返回遵循ProtocolA或ProtocolB的对象数组——这里专门定义了父协议Protocol_A_Or_B作为两个子协议的共同父类型,相关实现代码如下:
enum MainEnum_: Int, Identifiable, Hashable, CaseIterable { case One case Two case Three case Four case Five var id: Int { rawValue } var aOrBEnumArray: [Protocol_A_Or_B] { switch self { case .One: return EnumTypeA.allCases case .Two: return EnumTypeB.allCases default: return [] } } } enum EnumTypeA: Int, ProtocolA { case Option1 case Option2 case Option3 var id: Int { rawValue } } enum EnumTypeB: Int, ProtocolB { case OptionA case OptionB case OptionC var id: Int { rawValue } }
上述代码本身可以正常编译,但当尝试将遵循Protocol_A_Or_B的数组传入自定义View时,会触发编译报错:
Value of protocol type 'Protocol_A_Or_B' cannot conform to 'Hashable'; only struct/enum/class types can conform to protocols Value of protocol type 'Protocol_A_Or_B' cannot conform to 'Identifiable'; only struct/enum/class types can conform to protocols
报错出现在TheContentView2(data: arrayEnumTypeA)与TheContentView2(data: arrayEnumTypeB)两行,对应的View调用代码如下:
struct EnumProtocolsTest: View { var arrayEnumTypeA: [Protocol_A_Or_B] = MainEnum_.One.aOrBEnumArray var arrayEnumTypeB: [Protocol_A_Or_B] = MainEnum_.Two.aOrBEnumArray var body: some View { VStack { ScrollView(.horizontal, showsIndicators: false) { HStack { TheContentView2(data: MainEnum_.allCases) { item in Text("\(item.name)") .padding() .background(Color.purple) } } } ScrollView(.horizontal, showsIndicators: false) { HStack { TheContentView2(data: arrayEnumTypeA) { item in Text("\(item.id)") .padding() .background(Color.purple) } } } ScrollView(.horizontal, showsIndicators: false) { HStack { TheContentView2(data: arrayEnumTypeB) { item in Text("\(item.id)") .padding() .background(Color.purple) } } } } } }
根据代码逻辑可以判断,报错和自定义ViewTheContentView2的泛型约束直接相关:该View要求传入的数组元素必须同时遵循Identifiable与Hashable协议,其原始定义如下:
struct TheContentView2<Data: RandomAccessCollection, ElementView: View>: View where Data.Element: Identifiable, Data.Element: Hashable { var data: Data var itemView: (Data.Element) -> ElementView var body: some View { ForEach(data) { item in itemView(item) .padding() .background(Color.purple) } } }
- Swift 的*存在类型(existential type)*本身,无法直接用来满足其他协议的编译约束
- 定义的
[Protocol_A_Or_B]是装载了存在类型的数组,编译器仅能知道数组元素"可能"遵循Identifiable、Hashable,但无法在编译期完成类型校验——因为Protocol_A_Or_B本身没有声明自身继承自这两个协议,所以它的存在类型实例不能直接作为符合约束的类型,传入带泛型要求的View - 当前泛型View要求传入的元素是确定的具体类型,而不是"任意符合某个子协议的不透明存在类型"
补全父协议的继承关系(优先推荐)
把父协议的定义修改为直接继承所有子协议共有的能力,这样存在类型本身就满足全部约束:// 空父协议调整为继承所有公共能力 protocol Protocol_A_Or_B: Identifiable, Hashable, CaseIterable { } // 子协议仅保留区分逻辑,无需重复声明公共约束 protocol ProtocolA: Protocol_A_Or_B { } protocol ProtocolB: Protocol_A_Or_B { }改动完成后,
Protocol_A_Or_B的存在类型天然满足Identifiable、Hashable的约束,传入View时编译器不会再报"协议不能遵循协议"的错误。类型擦除临时适配
如果不想修改父协议的继承关系,可以在返回数组时,用AnyHashable+AnyIdentifiable的类型擦除容器包裹每个元素,让元素变成具体的、符合约束的类型再传入View。这种方式会丢失元素原本的类型信息,仅适合临时适配场景,长期维护成本较高。泛型化返回值替代存在类型
不直接返回存在类型数组,而是调整计算属性的返回逻辑,输出带具体类型的泛型值,从根源上避免存在类型的使用:func getAOrBArray<T: Protocol_A_Or_B>(for type: T.Type) -> [T]? { switch self { case .One: return EnumTypeA.allCases as? [T] case .Two: return EnumTypeB.allCases as? [T] default: return nil } }调用时直接传入具体的枚举类型,拿到的就是确定类型的数组,可以直接传入泛型View,不需要额外的类型擦除逻辑。
提示:Swift 6 对存在类型的语法要求会更严格,任何不带
any标记的协议类型作为值使用,都会触发编译警告。提前补全父协议的继承关系,可以大幅降低后续版本迁移的改动量。
内容的提问来源于stack exchange,提问作者Aнгел

