Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@smrfeld
Last active January 14, 2022 10:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smrfeld/c0780168c5cf819f200973f6f211dd57 to your computer and use it in GitHub Desktop.
Save smrfeld/c0780168c5cf819f200973f6f211dd57 to your computer and use it in GitHub Desktop.
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

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