如何将手动数据附加到可编码数组结构中?

时间:2019-04-17 05:09:58

标签: arrays swift struct

我想将手动数据附加到我的Array的struct对象上。

我想最后在数组中添加“ ALL”类别名称。

struct CategoryNameList : Codable {

    let categoryID : Int?
    var categoryImageURL : String?
    var categoryName : String?
    var isSelected : Bool?

    enum CodingKeys: String, CodingKey {
        case categoryID = "CategoryID"
        case categoryImageURL = "CategoryImageURL"
        case categoryName = "CategoryName"
        case isSelected = "isSelected"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        categoryID = try values.decodeIfPresent(Int.self, forKey: .categoryID)
        categoryImageURL = try values.decodeIfPresent(String.self, forKey: .categoryImageURL)
        categoryName = try values.decodeIfPresent(String.self, forKey: .categoryName)
        isSelected = try values.decodeIfPresent(Bool.self, forKey: .isSelected)
    }

}

1 个答案:

答案 0 :(得分:0)

您可以为此创建一个特殊的init并在创建手动实例时使用,将此init方法添加到当前结构CategoryNameList

struct CategoryNameList : Codable {
   //existing stuff

    init(categoryName: String) {
        self.categoryID = nil
        self.categoryName = categoryName    
    }
}

let all = CategoryNameList(categoryName: "All")
categoryNameArray.append(all)