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

前端 未结 3 1607
我寻月下人不归
我寻月下人不归 2021-02-18 23:33

Running Xcode 12, my Swift 5 Xcode project now has warnings whenever a Decodable or Codable type declares a let constant with an initial v

3条回答
  •  伪装坚强ぢ
    2021-02-18 23:53

    Solution: define an explicit CodingKeys enum to prevent id from decoded. For example,

    struct Course: Identifiable, Decodable {
      let id = UUID()
      let name: String
    
      private enum CodingKeys: String, CodingKey {
        case name
      }
      
      init(name: String) { self.name = name }
      init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let name = try container.decodeIfPresent(String.self, forKey: .name)
        self.name = name ?? "default-name"
      }
    }
    

提交回复
热议问题