首页 > 解决方案 > 将存储的struct数据修改为其他结构

问题描述

struct myStruct1: Codable {
    var field1: String
    var field2: String
    enum CodingKeys: String, CodingKey {
        case field1 = "field1"
        case field2 = "field2"
    }

//Storing the Values to the local file,
//[{"field1":"someValue1","field2":"someValue2"},{"field1":"someValue3","field2":"someValue4"}]

//Now i changed the struct to store an additional field as,

struct myStruct1: Codable {
var field1: String
var field2: String
var field3: String
enum CodingKeys: String, CodingKey {
    case field1 = "field1"
    case field2 = "field2"
    case field3 = "field3"
}

从现在开始,文件中将存储三个字段值,但是对于已经存储的数据将只有两个字段,我需要将新添加field3的默认值更新someValue0到文件中存储的数据中,我该如何实现.

我清楚了吗?

标签: iosswiftfilestruct

解决方案


您可以将其设为可选

 var field3: String?

并分配稍后或更好的写入init并赋予其价值

struct myStruct1: Codable {
  var field1: String
  var field2: String
  var field3: String
  enum CodingKeys: String, CodingKey {
      case field1 = "field1"
      case field2 = "field2"
      case field3 = "field3"
  }

      init(from decoder: Decoder) throws {
          let values = try decoder.container(keyedBy: CodingKeys.self)
          field1 = try values.decode(String.self, forKey: .field1)
          field2 = try values.decode(String.self, forKey: .field2)
          field3 = "someValue0"
    }
}

如果filed3存在,那么做

field3 = try values.decodeIfPresent(String.self, forKey: .field3) ?? ""

推荐阅读