Skip to content

Instantly share code, notes, and snippets.

@hiragram
Created March 20, 2017 04:16
Show Gist options
  • Select an option

  • Save hiragram/21ea34cb05649f40a76671fa2856604e to your computer and use it in GitHub Desktop.

Select an option

Save hiragram/21ea34cb05649f40a76671fa2856604e to your computer and use it in GitHub Desktop.
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:)' ②が呼ばれてほしい
@hiragram
Copy link
Author

②のメソッドを消すと、22行目がエラーになるようにしたい ということかな

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment