【问题标题】:Parsing unsigned integer from JSON dictionary in Swift在 Swift 中从 JSON 字典中解析无符号整数
【发布时间】:2015-01-25 23:47:49
【问题描述】:

我正在尝试编写代码以将 JSON 值(可以是 JSON 中的字符串或整数)解析为 可选的无符号整数(即UInt?),以容忍值丢失或不可解析 - 如果源数据包含合法的正值,我只希望结果具有值:

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)
}

这看起来非常笨拙。真的有这么难吗?

【问题讨论】:

    标签: json swift int unsigned-integer


    【解决方案1】:

    你可以这样做:

    var numLikesUnsigned = (jsonDictionary["likeCount"]?.integerValue).map { UInt($0) }
    

    由于NSStringNSNumber 都具有integerValue 属性,所以无论是哪种类型,我们都可以访问.integerValue

    let dict:NSDictionary = ["foo":42 , "bar":"42"]
    
    let foo = dict["foo"]?.integerValue // -> 42 as Int?
    let bar = dict["bar"]?.integerValue // -> 42 as Int?
    

    而且,Optional.map 方法:

    /// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
    func map<U>(f: (T) -> U) -> U?
    

    你可以:

    let intVal:Int? = 42
    let uintVal = intVal.map { UInt($0) } // 42 as UInt?
    

    代替:

    let intVal:Int? = 42
    
    let uintVal:UInt?
    if let iVal = intVal {
        uintVal = UInt(iVal)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多