我有这样的结构:
struct OrderLine: Codable{
let absUrl: String?
let restApiUrl : String?
let description : String?
let quantity : Int?
let subscription: Subs?
let total: Double?
}
struct Subs: Codable{
let quantity: Int?
let name: String?
}
和一些OrderLine
在服务器响应中
"subscription": {
"quantity": 6,
"name": "3 Months"
},
但有时它具有String
类型:
"subscription": "",
没有subscription
的话一切正常,但是出现错误
CodingKeys(stringValue: "subscription", intValue: nil)],
debugDescription: "Expected to decode Dictionary<String, Any>
but found a string/data instead.", underlyingError: nil)
所以我的问题是-如何解码或解码为值String?
的{{1}}或解码为""
而没有任何错误?
ps。如果我仅像Subs?
那样解码,则会出现错误String?
答案 0 :(得分:2)
您只需要自己实现init(from:)
并尝试将subscription
密钥的值解码为代表Dictionary
的{{1}}和Subs
即可。
String