Last active
August 29, 2015 14:24
-
-
Save 0thernet/0faa057314ae1502d764 to your computer and use it in GitHub Desktop.
enumFrom
This file contains hidden or 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
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