Created
February 15, 2018 00:34
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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