Created
March 20, 2017 04:16
-
-
Save hiragram/21ea34cb05649f40a76671fa2856604e to your computer and use it in GitHub Desktop.
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
| public extension Dictionary { | |
| // ① | |
| func get<T>(valueForKey key: Key) throws -> T { | |
| guard let value = self[key] as? T else { | |
| throw DictionaryExtractionError.castFailed(key: String.init(describing: key), actualValue: self[key]) | |
| } | |
| return value | |
| } | |
| // ② | |
| func get<T>(valueForKey key: Key) throws -> Optional<T> { | |
| return self[key] as? T | |
| } | |
| } | |
| let json: [String: Any] = [ | |
| "hoge": 1, | |
| "fuga": "hello", | |
| ] | |
| let hoge: Int = try json.get(valueForKey: "hoge") // ①が呼ばれて hogeはInt | |
| let fuga: String? = try json.get(valueForKey: "fuga") // error: Ambiguous use of 'get(valueForKey:)' ②が呼ばれてほしい |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
②のメソッドを消すと、22行目がエラーになるようにしたい ということかな