0
votes

Make conforming struct to Codable (Encodable & Decodable) protocol is super easy: just declare it. But do I have to write all boiler code (CodingEnum, init(from decoder: Decoder), encode(to encoder: Encoder), etc) if I want make class conforming to Codable?

1

1 Answers

1
votes

No, you haven't to do it. Example:

import Foundation

class Message: Codable {
    let id: Int = 1
    let text: String = "Hello"
}

let message = Message()
let encoder = JSONEncoder()
let json = try encoder.encode(message)
print(String(data: json, encoding: String.Encoding.utf8)!)