swift4 Codable Decodable Encodable
程序员文章站
2024-02-20 15:37:46
...
extension Encodable {
func toData() -> Data? {
let encoder = JSONEncoder()
return try?encoder.encode(self)
}
}
extension Decodable {
static func toModel(from data: Data) -> Self? {
let decoder = JSONDecoder()
return try? decoder.decode(Self.self, from: data)
}
}