I'm trying to write code to parse a JSON value (which could be a String or an Integer in the JSON) to an optional unsigned integer (i.e. UInt?
), being tolerant to the value being missing or not being parsable - I only want the result to have a value if the source data contains a 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. Is it really this hard?
you can simply do like this:
Since
NSString
andNSNumber
both hasintegerValue
property, we can access.integerValue
no matter which type is that.And,
Optional
has.map
method:You can:
instead of: