Skip to content

Instantly share code, notes, and snippets.

@zmcartor
Last active March 23, 2017 19:05
Show Gist options
  • Save zmcartor/320338a004acc512c1ecb2d0b67aef5f to your computer and use it in GitHub Desktop.
Save zmcartor/320338a004acc512c1ecb2d0b67aef5f to your computer and use it in GitHub Desktop.
Unwrap from JSON dict with default value
func unwrap<T:Any>(dictionary:[String : AnyObject], key:String, defaultValue:T) -> T {
let value = dictionary[key] as? T ?? defaultValue
return value as T
}
// Can be curried inside a init?(json:NSDictionary) function
let stringAtKey:(String) -> String = { key in
return unwrap(dictionary , key:key, defaultValue:"")
}
let numberAtKey:(String) -> NSNumber = { key in
return unwrap(dictionary , key:key, defaultValue:NSNumber(int:0))
}
let boolAtKey:(String) -> Bool = { key in
return unwrap(dictionary , key:key, defaultValue:false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment