Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
convert array of strings to enums
extension Array where Element == String {
public func to_enums<T: RawRepresentable>() -> [T] where T.RawValue == String {
let wrapped: [T?] = self.map { T(rawValue: $0) }
return wrapped.filter { $0 != nil } as! [T]
}
}
@jgoldschmidt
Copy link

jgoldschmidt commented Dec 20, 2021

extension Array where Element == String {
    public func to_enums<T: RawRepresentable>() -> [T] where T.RawValue == String {
        let wrapped: [T] = self.compactMap { T(rawValue: $0) }
        return wrapped
    }
}

Then no more filter neither force casting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment