为什么从 JSON 返回的值不能与 NSNull 相比较?
Why value returned from JSON is not comparable to NSNull?
我正在通过 Swift 4 JSON Codable 方法从 API 返回字符串值。
我知道很少有值是 "null" 或 nil,所以为了避免崩溃,我正在尝试实现代码。这是给出主题错误的代码(在 NSNull 比较上):
if Cur[indexPath.row].cap == nil || Cur[indexPath.row].cap == NSNull {
print("Could not find the value")
CapVal = "N/A"
} else {
CapVal = Cur[indexPath.row].cap!
}
错误:
二元运算符 '==' 不能应用于 'String?' 和 'NSNull.Type
类型的操作数
我也尝试将其转换为字符串:Cur[indexPath.row].cap as? String
仍然遇到同样的错误。
如果您使用 JSONDecoder
,缺失值和明确指定为 null
的值都将 return 编辑为 nil
:
考虑这个 JSON:
{"foo": "a", "bar": null}
还有这个struct
:
struct Result: Decodable {
var foo: String
var bar: String?
var baz: String?
}
如果你使用JSONDecoder
,你可以这样做:
guard let result = try? JSONDecoder().decode(Result.self, from: data) else { ... }
let bar = result.bar ?? "N/A"
我知道你在 Swift 4 中询问 Codable
,但仅供参考,如果你使用 JSONSerialization
,理论上你可以测试 [=16] =],因为 JSONSerialization
确实 return null
值为 NSNull
:
guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { ... }
let bar = json["bar"]
if bar == nil || bar is NSNull {
// bar was either not found or `null`
} else {
// bar was found and was not `null`
}
不过,就个人而言,我只是选择性地转换为字符串并在转换失败时使用 nil
合并运算符,例如
let bar = (json["bar"] as? String) ?? "N/A"
但是,这对于 Swift 4 的 JSONDecoder
来说毫无意义。
我正在通过 Swift 4 JSON Codable 方法从 API 返回字符串值。
我知道很少有值是 "null" 或 nil,所以为了避免崩溃,我正在尝试实现代码。这是给出主题错误的代码(在 NSNull 比较上):
if Cur[indexPath.row].cap == nil || Cur[indexPath.row].cap == NSNull {
print("Could not find the value")
CapVal = "N/A"
} else {
CapVal = Cur[indexPath.row].cap!
}
错误:
二元运算符 '==' 不能应用于 'String?' 和 'NSNull.Type
类型的操作数我也尝试将其转换为字符串:Cur[indexPath.row].cap as? String
仍然遇到同样的错误。
如果您使用 JSONDecoder
,缺失值和明确指定为 null
的值都将 return 编辑为 nil
:
考虑这个 JSON:
{"foo": "a", "bar": null}
还有这个struct
:
struct Result: Decodable {
var foo: String
var bar: String?
var baz: String?
}
如果你使用JSONDecoder
,你可以这样做:
guard let result = try? JSONDecoder().decode(Result.self, from: data) else { ... }
let bar = result.bar ?? "N/A"
我知道你在 Swift 4 中询问 Codable
,但仅供参考,如果你使用 JSONSerialization
,理论上你可以测试 [=16] =],因为 JSONSerialization
确实 return null
值为 NSNull
:
guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { ... }
let bar = json["bar"]
if bar == nil || bar is NSNull {
// bar was either not found or `null`
} else {
// bar was found and was not `null`
}
不过,就个人而言,我只是选择性地转换为字符串并在转换失败时使用 nil
合并运算符,例如
let bar = (json["bar"] as? String) ?? "N/A"
但是,这对于 Swift 4 的 JSONDecoder
来说毫无意义。