如何合并Swift泛型enumValue方法以支持可选/非可选关联类型
问题描述
我有如下代码,主要用于在适用场景下将字符串转换为枚举:
func value(for key: String) -> String? { return values(for: key).first } func anyValue<T: LosslessStringConvertible>(for key: String) -> T? { guard let value = value(for: key) else { return nil } return T(value) } func enumValue<EnumType, ValueType>(for key: String) -> EnumType? where EnumType: RawRepresentable<ValueType>, ValueType: LosslessStringConvertible { guard let value: ValueType = anyValue(for: key) else { return nil } return EnumType(rawValue: value) } func enumValue<EnumType, ValueType>(for key: String) -> EnumType? where EnumType: RawRepresentable<ValueType?>, ValueType: LosslessStringConvertible { guard let value: ValueType = anyValue(for: key) else { return nil } return EnumType(rawValue: value) }
请问能否在不新增协议或扩展的情况下,将这两个enumValue泛型方法合并为一个?我希望它既能支持RawRepresentable<Int>类型,也能支持RawRepresentable<Int?>类型。
解决方案
可以合并,只需要调整泛型约束,让单个方法同时适配可选与非可选的RawValue类型。以下是实现代码:
func enumValue<EnumType, ValueType>(for key: String) -> EnumType? where EnumType: RawRepresentable, ValueType: LosslessStringConvertible, EnumType.RawValue == ValueType || EnumType.RawValue == ValueType? { guard let rawValue = anyValue(for: key) as? EnumType.RawValue else { return nil } return EnumType(rawValue: rawValue) }
说明
- 泛型约束新增了
EnumType.RawValue == ValueType || EnumType.RawValue == ValueType?,同时允许枚举的原始值为ValueType或ValueType?两种类型 - 通过
as? EnumType.RawValue将anyValue返回的ValueType?转换为枚举所需的原始值类型,自动适配可选与非可选场景 - 完全保留了原两个方法的逻辑:当无法从字符串解析出对应值时返回
nil,解析成功则尝试创建枚举实例
这个实现不需要新增任何协议或扩展,同时支持RawRepresentable<Int>和RawRepresentable<Int?>类型的枚举转换。
内容的提问来源于stack exchange,提问作者mckeed
相关产品推荐
相关产品推荐

