Skip to content

Instantly share code, notes, and snippets.

@cemaleker
Last active October 16, 2019 19:39
Show Gist options
  • Save cemaleker/155c99a7ef45e26dbaa793427e0a829c to your computer and use it in GitHub Desktop.
Save cemaleker/155c99a7ef45e26dbaa793427e0a829c to your computer and use it in GitHub Desktop.
StringRepresentable casting with generics
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