Parsing unsigned integer from JSON dictionary in Swift -
i'm trying write code parse json value (which string or integer in json) optional unsigned integer (i.e. uint?
), being tolerant value being missing or not being parsable - want result have value if source data contains legitimate positive value:
convenience init(jsondictionary: nsdictionary) { ... var numlikesunsigned: uint? if let likesobj: anyobject = jsondictionary.valueforkey("likecount") { let likes = "\(likesobj)" if let numlikessigned = likes.toint() { numlikesunsigned = uint(numlikessigned) } } self.init(numlikesunsigned) }
this seems incredibly unwieldy. hard?
you can this:
var numlikesunsigned = (jsondictionary["likecount"]?.integervalue).map { uint($0) }
since nsstring
, nsnumber
both has integervalue
property, can access .integervalue
no matter type that.
let dict:nsdictionary = ["foo":42 , "bar":"42"] let foo = dict["foo"]?.integervalue // -> 42 int? let bar = dict["bar"]?.integervalue // -> 42 int?
and, optional
has .map
method:
/// if `self == nil`, returns `nil`. otherwise, returns `f(self!)`. func map<u>(f: (t) -> u) -> u?
you can:
let intval:int? = 42 let uintval = intval.map { uint($0) } // 42 uint?
instead of:
let intval:int? = 42 let uintval:uint? if let ival = intval { uintval = uint(ival) }
Comments
Post a Comment