swift 4 Codable-如果有字符串或字典,如何解码?

时间:2019-01-07 16:13:06

标签: swift codable

我有这样的结构:

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?

1 个答案:

答案 0 :(得分:2)

您只需要自己实现init(from:)并尝试将subscription密钥的值解码为代表Dictionary的{​​{1}}和Subs即可。

String