Skip to content

Instantly share code, notes, and snippets.

@grigorye
Created February 15, 2018 00:34
Show Gist options
  • Save grigorye/0f5dc48534bd303a02c9f5b073802ed7 to your computer and use it in GitHub Desktop.
Save grigorye/0f5dc48534bd303a02c9f5b073802ed7 to your computer and use it in GitHub Desktop.
Recover Swift enum given its name (in case you can not have String as RawValue)
//: Playground - noun: a place where people can play
extension RawRepresentable where RawValue: BinaryInteger {
init?(named name: String, from lower: Self, to upper: Self) {
var i = lower.rawValue
repeat {
let x = Self(rawValue: i)!
guard "\(x)" != name else {
self = x
return
}
i += 1
} while i <= upper.rawValue
return nil
}
}
enum A : Int {
case foo
case bar
case baz
}
let names = ["foo", "bar", "baz", "qux"]
names.map {
A(named: $0, from: .foo, to: .baz)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment