Skip to content

Instantly share code, notes, and snippets.

@alfavata
Last active August 5, 2020 13:13
Show Gist options
  • Save alfavata/f9b6a6c6fc5d73b224a9c14744ffd9a1 to your computer and use it in GitHub Desktop.
Save alfavata/f9b6a6c6fc5d73b224a9c14744ffd9a1 to your computer and use it in GitHub Desktop.
Codable doesn't play nicely with subclasses
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