Last active
October 16, 2019 19:39
-
-
Save cemaleker/155c99a7ef45e26dbaa793427e0a829c to your computer and use it in GitHub Desktop.
StringRepresentable casting with generics
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
enum StringRepresentableType: String { | |
case foo | |
case bar | |
} | |
typealias JSONDictionary = [String: Any] | |
extension JSONDictionary { | |
func value<T, R>(for key: String) -> T? where T: RawRepresentable, T.RawValue == R { | |
guard let rawValue = self[key] as? R, | |
let value = T(rawValue: rawValue) else { | |
return nil | |
} | |
return value | |
} | |
} | |
let barValue = StringRepresentableType(rawValue: "bar")! | |
let dict: JSONDictionary = ["fooKey": "foo", "barKey": "bar"] | |
if let value: StringRepresentableType = dict.value(for: "barKey") { | |
print(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment