Skip to content

Instantly share code, notes, and snippets.

@vprtwn
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vprtwn/0faa057314ae1502d764 to your computer and use it in GitHub Desktop.
Save vprtwn/0faa057314ae1502d764 to your computer and use it in GitHub Desktop.
enumFrom
protocol StringDecodable {
init?(string: String)
}
extension Dictionary where Key: JSONKey, Value: AnyObject {
/// Converts a string to an enum value
func enumFrom<T: StringDecodable>(key: Key, _ enumType: T.Type) -> T? {
if let s = self[key] as? String {
return enumType.init(string: s)
}
return nil
}
}
private enum TestEnum: StringDecodable {
case Foo
init(string: String) { self = .Foo }
}
let d = ["foo": "bar"]
let result = d.enumFrom("foo", TestEnum.self)
// (!) Cannot invoke 'enumFrom' with an argument list of type '(String, TestEnum.Type)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment