简体   繁体   English

如何在 swift 的 struct codable 中存储任何未定义的变量

[英]How to store any undefined variable in struct codable in swift

I have a struct like -我有一个像这样的结构 -

struct Attachment : Codable {
var reviewA : [String]?
var reviewB : String?
}

Now earlier the API was returning string only which I can set in reviewB but now it has 3 cases.现在早些时候 API 只返回我可以在reviewB中设置的字符串,但现在它有 3 个案例。 It can either be empty string (""), array of strings(["",""]) or single string ("dummy").它可以是空字符串 ("")、字符串数组 (["",""]) 或单个字符串 ("dummy")。 Now, my console gives error - Expected to decode String but found an array instead现在,我的控制台出现错误 - Expected to decode String but found an array instead

How should I resolve it?我该如何解决?

You can all time use array你可以一直使用数组

let json = """
{
    "reviewA": ["H"],
    "reviewB": "H"
}
"""

let jsonData = json.data(using: .utf8)!

struct Attachment: Codable {
    var reviewA:    [String]?
    var reviewB:    [String]?
    
    private enum Keys: String, CodingKey {
        case reviewA
        case reviewB
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Keys.self)
        
        self.reviewA = try container.decode([String].self, forKey: .reviewA)
        
        if let arr = try? container.decode([String].self, forKey: .reviewB) {
            self.reviewB = arr
        } else {
            let str = try container.decode(String.self, forKey: .reviewB)
            self.reviewB = [str]
        }
    }
}


let model = try! JSONDecoder().decode(Attachment.self, from: jsonData)
print(model)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM