Last active
March 23, 2017 19:05
-
-
Save zmcartor/320338a004acc512c1ecb2d0b67aef5f to your computer and use it in GitHub Desktop.
Unwrap from JSON dict with default value
This file contains 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
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