Last active
August 5, 2020 13:13
-
-
Save alfavata/f9b6a6c6fc5d73b224a9c14744ffd9a1 to your computer and use it in GitHub Desktop.
Codable doesn't play nicely with subclasses
This file contains 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 Foundation | |
class C: Codable { | |
var p: String? | |
} | |
class D: C { | |
var q: String? | |
} | |
let c = C() | |
c.p = "P in C" | |
let d = D() | |
d.p = "P in D" | |
d.q = "Q in D" | |
let cData = try! JSONEncoder().encode(c) | |
let dData = try! JSONEncoder().encode(d) | |
let cDecoded = try! JSONDecoder().decode(C.self, from: cData) | |
print(cDecoded.p ?? "Nope") | |
let dDecoded = try! JSONDecoder().decode(D.self, from: dData) | |
print(dDecoded.p ?? "Nope") | |
print(dDecoded.q ?? "Nope") | |
let subclassDecoded = try! JSONDecoder().decode(C.self, from: dData) | |
print(subclassDecoded.p ?? "Nope") | |
// print(subclassDecoded.q ?? "Nope") // won't compile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment