Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created June 5, 2014 02:32
Show Gist options
  • Save mikeash/bbc96cf19327c9b9fba1 to your computer and use it in GitHub Desktop.
Save mikeash/bbc96cf19327c9b9fba1 to your computer and use it in GitHub Desktop.
protocol Lookuper {
func get<T: NSObject>(key: String) -> T?
}
struct KeyError {
var key: String
var desiredType: NSObject.Type
var actualType: Any.Type
func simpleDescription() -> String {
return "key: \(key), desired: \(desiredType.className), actual: \(actualType)"
}
}
class DictLookuper : Lookuper {
let dict: Dictionary<String, AnyObject>
var errors = KeyError[]()
init(dict: Dictionary<String, AnyObject>) {
self.dict = dict
}
func get<T: NSObject>(key: String) -> T? {
let value: AnyObject? = dict[key]
let typedValue = value as? T
if !typedValue {
println("with error!");
errors.append(KeyError(key: key, desiredType: T.self, actualType: value.dynamicType))
}
return typedValue
}
}
func With(dict: Dictionary<String, AnyObject>, block: (Lookuper) -> Void) -> KeyError[] {
let lookuper = DictLookuper(dict: dict)
block(lookuper)
return lookuper.errors
}
let errors = With(jsonDict) { lookuper in
let a: NSString? = lookuper.get("a")
let c: NSNumber? = lookuper.get("c")
let a_: NSNumber? = lookuper.get("a")
let c_: NSString? = lookuper.get("c")
println(a, c, a_, c_)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment