0

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?

zzheads
  • 1,368
  • 5
  • 28
  • 57

1 Answers1

1

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)!)
Max Potapov
  • 1,267
  • 11
  • 17