Lista kluczy do kodowania / dekodowania jest kontrolowana przez typ o nazwie CodingKeys(zwróć uwagę sna koniec). Kompilator może zsyntetyzować to za Ciebie, ale zawsze może to zastąpić.
Załóżmy, że chcesz wykluczyć właściwość nicknamezarówno z kodowania, jak i dekodowania:
struct Person: Codable {
var firstName: String
var lastName: String
var nickname: String?
private enum CodingKeys: String, CodingKey {
case firstName, lastName
}
}
Jeśli chcesz, aby był asymetryczny (tj. Koduje, ale nie dekoduje lub odwrotnie), musisz dostarczyć własne implementacje encode(with encoder: )i init(from decoder: ):
struct Person: Codable {
var firstName: String
var lastName: String
var fullName: String {
return firstName + " " + lastName
}
private enum CodingKeys: String, CodingKey {
case firstName
case lastName
case fullName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(firstName, forKey: .firstName)
try container.encode(lastName, forKey: .lastName)
try container.encode(fullName, forKey: .fullName)
}
}
CodingKeyswyliczeniem.