Last active
August 3, 2018 12:07
-
-
Save aodhol/b469a294d3c42306d2bbcb8b84ddd8d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class Animal: Codable { | |
var say: String? | |
private enum CodingKeys : String, CodingKey { | |
case say | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: CodingKeys.self) | |
try container.encode(say, forKey: .say) | |
} | |
init(say: String) { | |
self.say = say | |
} | |
} | |
class Dog: Animal { | |
var collarName: String? | |
private enum CodingKeys: String, CodingKey { | |
case collarName | |
case dog // not strictly necessary but nests the subclass specific fields in the resultant JSON. | |
} | |
override func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: CodingKeys.self) | |
try super.encode(to: container.superEncoder(forKey: .dog)) | |
try container.encode(collarName, forKey: .collarName) | |
} | |
required init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
collarName = try container.decode(String.self, forKey: .collarName) | |
let superDecoder = try container.superDecoder(forKey: .dog) | |
try super.init(from: superDecoder) | |
} | |
init(say: String, collarName: String) { | |
super.init(say: say) | |
self.collarName = collarName | |
} | |
} | |
let c = Animal(say: "") | |
c.say = "P in Animal" | |
let d = Dog(say: "Woof", collarName: "Barney") | |
print(d.collarName ?? "Nope") | |
let cData = try! JSONEncoder().encode(c) | |
let dData = try! JSONEncoder().encode(d) | |
let cDecoded = try! JSONDecoder().decode(Animal.self, from: cData) | |
print(cDecoded.say ?? "Nope") | |
let dDecoded = try! JSONDecoder().decode(Dog.self, from: dData) | |
print(dDecoded.say ?? "Nope") | |
print(dDecoded.collarName ?? "Nope") | |
let subclassDecoded = try! JSONDecoder().decode(Animal.self, from: dData) | |
print(subclassDecoded.say ?? "Nope") | |
// Print the JSON: | |
let encoder = JSONEncoder() | |
encoder.outputFormatting = .prettyPrinted | |
let encodedDog = try? encoder.encode(d) | |
print(String(data: encodedDog!, encoding: .utf8)!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment