【发布时间】:2017-09-18 06:25:18
【问题描述】:
- 我想检查 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/…)
-
我想检查一下“
” -
如果你的意思是字符串
<null>,你可以检查if max == "<null>"。如果你的意思是 Swift 值 nil,你应该使用 null 合并运算符:MaxValue = blahblah ?? 0 -
实际上将任何非数字字符串扔到
as? Int将导致nil,所以这可能是要走的路。 -
这是斯威夫特。不要使用
NSArray,这样可以避免像... as AnyObject).value(forKey: "maxprice")这样的可怕语法,也不要使用valueForKey,除非你能解释为什么需要KVC。为什么NSNumber? Swift 中有原生类型(Int、Double)