We are using Swift 5.0. I need to turn a list of strings into a set of enum cases regularly. I wrote a Kotlin function easily that takes an enum class at runtime and a list of strings, and converts it to a Java EnumSet (well, 2 functions that work together):
fun <EnumT : Enum<EnumT>> ConvertStrToEnum(enumClass: Class<EnumT>, str: String?): EnumT? {
if (str == null)
return null
for (enumval in enumClass.enumConstants) {
if (enumval.toString() == str)
return enumval
}
throw IllegalArgumentException("Gave an invalid enum value for class ${enumClass.canonicalName}: [$str]")
}
fun <EnumT : Enum<EnumT> > ConvertStrArrayToEnumSet(enumClass: Class<EnumT>, array: List<String>?) : EnumSet<EnumT> {
val set = EnumSet.noneOf(enumClass)
array?.forEach { value -> ignoreExceptions { set.add(ConvertStrToEnum(enumClass, value)) } }
return set
}
And, to be clear, an actual usage is:
var intent: EnumSet<Intent>
intent = ConvertStrArrayToEnumSet(Intent::class.java, filters.array(MatchFilter.Intent.jsonName))
Can I write a function in Swift 5 that achieves the same result? I wrote this for one conversion, here's the example. If I can't write this function I will have this boilerplate code repeated throughout the app.
public var intents: Set<Intent>
if let jsonIntents = filters?["intent"] as? Array<String> {
for jsonIntent in jsonIntents {
if let intent = Intent(rawValue: jsonIntent) {
intents.insert(intent)
}
}
}