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
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"
}
}