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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,254 times
        
    1 Answers
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
- 
                    Please read my question again, I’m asking about CLASS, not struct – zzheads Sep 21 '17 at 08:58
- 
                    classes working as well. example changed to class usage. – Max Potapov Sep 21 '17 at 09:02
- 
                    Found why my class can not "auto-conform" to Codable, because it has property of Dictionary [String: Any] (JSON). So how to make Dictionaryconform to Codable? – zzheads Sep 21 '17 at 09:06
- 
                    `[String: Any]` can't conform for `Codable` because `Any` doesn't conform to `Codable` protocol. – Max Potapov Sep 21 '17 at 09:12
- 
                    @zzheads https://stackoverflow.com/a/44670454/2778645 here is a link with answer you could help with 'Any' conformance issue. – Max Potapov Sep 21 '17 at 09:41
