I have the following code that basically converts strings to Enums where applicable:
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)
}
Is it possible to combine the two versions of enumValue
into one generic without any new protocols or extensions? I want to be able to use it with a RawRepresentable<Int>
as well as a RawRepresentable<Int?>
.