代码之家  ›  专栏  ›  技术社区  ›  Albert

创建可识别的id会给出不可更改的警告

  •  0
  • Albert  · 技术社区  · 3 年前

    我有以下几点:

    struct myModel: Decodable, Identifiable {
        let id = UUID()
        let a, b, c: String
    }
    

    我收到以下警告:

    enter image description here

    Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten
    

    我不想在数据刷新后更改id,我只想分配一次。我怎样才能摆脱那个警告呢?

    2 回复  |  直到 3 年前
        1
  •  1
  •   vadian    3 年前

    要么宣布 id var 或者加上 CodingKeys 省略 身份证件 .

    请总是以大写字母开头命名结构和类

    struct MyModel: Decodable, Identifiable {
        private enum CodingKeys: String, CodingKey { case a, b, c } 
    
        let id = UUID()
        let a, b, c: String
    }
    
        2
  •  1
  •   TheLivingForce    3 年前

    马上 myModel 符合可编码的存档要求。解码时,ID将设置为新的UUID,而不是文件中“ID”字段中定义的UUID。

    如果您想在解码结构时保留ID(比如,如果您将其写入一个文件,并且在读回时想要相同的ID),请删除内联初始值设定项,并编写一个以a、b和c为参数的完整初始值设定项。

    如果解码时不想保留ID,忽略警告并保持代码不变就足够了。