我正在使用 Swift 4 和JSONDecoder
. 我有以下结构:
struct Customer: Codable {
var id: Int!
var cnum: String!
var cname: String!
}
注意:这些字段不能设为可选。
现在我有一个 JSON 字符串:
[
{
"id": 1,
"cnum": "200",
"cname": "Bob Smith"
},
{
"id": 2,
"cnum": "201",
"cname": null
}
]
为了解码它,我使用以下内容:
let decoder = JSONDecoder()
let customers = try decoder.decode([Customer].self, from: json)
一切正常,除了 null 数据被转换为 nil。我的问题是,将传入的 nil 转换为空字符串(“”)的最简单方法是什么?
我想用最少的代码来做到这一点,但我不确定正确的方法以及在什么时候可以将 nil 转换为空字符串。事先谢谢你。