我有符合Codable
协议的encode
。我实现了自定义JSONEncoder
-func,以便可以控制编码过程。但是我并不需要在所有情况下都使用这种自定义编码,有时我想依靠Foundation本身的编码。可以告诉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)!)
我想要哪种编码方式(例如创建编码策略)?
这是我的代码的简化版本:
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)
}
更新
要回答其中一项评论:并不是要包含或排除一个属性,而是要更改属性的类型或内容:
{{1}}