【问题标题】:how to check condition with "<null>" in swift 3.0如何在 swift 3.0 中使用“<null>”检查条件
【发布时间】:2017-09-18 06:25:18
【问题描述】:
  1. 我想检查 maxprice 是否等于 "" 如果它是 "" 那么 maxprice 将变为 maxprice = 0

我的 Json

price = ({
    maxprice = "<null>";
    minprice = "<null>";
});

代码

var Arr = NSArray()

Arr = result.value(forKey: "price") as! NSArray
let max = Arr.value(forKey: "maxprice")

if max == nil {
    self.MaxValue = 0
    self.MinValue = 0
}

else {
    let maxval =  (Arr.object(at: 0) as AnyObject).value(forKey: "maxprice") as! NSNumber
    let min =  (Arr.object(at: 0) as AnyObject).value(forKey: "minprice") as! NSNumber

    self.MaxValue = maxval
    self.MinValue = min
}

错误:无法将“NSNull”类型的值 (0x102148918) 转换为 'NSNumber' (0x10311c4a8)。

【问题讨论】:

  • 如果你想要字符串为“”(空)那么你可以使用 string.isEmpty (检查这个问题stackoverflow.com/questions/24133157/…
  • 我想检查一下“
  • 如果你的意思是字符串&lt;null&gt;,你可以检查if max == "&lt;null&gt;"。如果你的意思是 Swift 值 nil,你应该使用 null 合并运算符:MaxValue = blahblah ?? 0
  • 实际上将任何非数字字符串扔到as? Int 将导致nil,所以这可能是要走的路。
  • 这是斯威夫特。不要使用NSArray,这样可以避免像... as AnyObject).value(forKey: "maxprice") 这样的可怕语法,也不要使用valueForKey,除非你能解释为什么需要KVC。为什么NSNumber? Swift 中有原生类型(IntDouble

标签: ios swift swift3


【解决方案1】:

您也可以使用is 来检查是否存在空值:

if Arr.value(forKey: "maxprice") is NSNull {
    // do something with null JSON value here
}

【讨论】:

  • 这是ObjectiveC风格吗?我认为在 Swift 中你想要 if Blah == nil { ... },或者更好的是,同时使用 if let unboxed = Blah { // use unboxed } 解开可选项
  • 这是在快速检查值是否为空。
【解决方案2】:

Swift 3.0

您可以使用?? 在短代码行中获得此信息,如下所示,我们也可以说是救援操作。

let max = Arr.value(forKey: "maxprice") as? NSNumber ?? 0

【讨论】:

    【解决方案3】:

    这是 Swift 的方式。

    使用可选绑定,不要使用objectivecishNSArrayvalueForKeyNSNumber

    你需要检查

    • 如果键 price 的值是一个 Swift 字典数组 ([[String:Double]])。 distinct 类型避免了对NSNull 的额外检查
    • 如果数组不为空。

    假设minpricemaxprice 应该是Double 值,如果不是用Int 替换Double

    if let priceArray = jsonDict["price"] as? [[String:Double]],
        let price = priceArray.first {
        minValue = price["minprice"] ?? 0.0
        maxValue = price["maxprice"] ?? 0.0
    } else {
        minValue = 0.0
        maxValue = 0.0
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-03
      • 2017-12-19
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      相关资源
      最近更新 更多