I have struct
that conforms to the Codable
-protocol. I implemented a custom encode
-func so that I have control over the encoding process. But I don't need this custom encoding in all cases, sometimes I want to rely on the encoding of Foundation itself. Is it possible to tell the JSONEncoder
what kind of encoding I want (like creating an encoding strategy)?
This is a simplified version of my code:
struct User: Codable {
var name: String
var age: Int
var phone: PhoneNumber
struct PhoneNumber: Codable {
var countryCode: Int
var number: Int
enum CodingKeys: CodingKey {
case countryCode, number
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// I would like to have control over the next line, so that either
// the countryCode is encoded or not, like:
// if conditon {
try container.encode(self.countryCode, forKey: .countryCode)
// }
try container.encode(self.number, forKey: .number)
}
}
}
let user = User(name: "John", age: 12, phone: User.PhoneNumber(countryCode: 49, number: 1234567))
let jsonData = try! JSONEncoder().encode(user)
print(String(data: jsonData, encoding: .utf8)!)
UPDATE
To answer one of the comments: It's not really about including or excluding one property, it's more about changing the type or content of a property:
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// if conditon {
try container.encode("\(self.countryCode)".data(using: .utf8), forKey: .countryCode)
// }
try container.encode(self.number, forKey: .number)
}