Polymorphically decode a sub-object of a KeyedDecodingContainer in Swift - swift

The following code attempts to create a Codable type AnyBase that would allow you to encode and decode various subclasses of Base. As written, in fails, because it tries to lookup the type objects by a string code, using getTypeFromCode. But if you use the commented-out part instead with hard-coded types, it prints "Sub1", as desired.
Is there a way to adjust this to use something like getTypeFromCode and eliminate the hard-coded types from init?
class Base: Codable {
var foo: Int = 1
var codingTypeKey: String { fatalError("abstract") }
}
class Sub1: Base {
var sub1Prop: Int = 2
override var codingTypeKey: String { "sub1" }
enum CodingKeys: CodingKey {
case sub1Prop
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
sub1Prop = try c.decode(Int.self, forKey: .sub1Prop)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(sub1Prop, forKey: .sub1Prop)
try super.encode(to: encoder)
}
}
class Sub2: Base {
var sub2Prop: Int = 2
override var codingTypeKey: String { "sub2" }
}
func getTypeFromCode(_ typeCode: String) -> Base.Type {
if typeCode == "sub1" { return Sub1.self }
else if typeCode == "sub2" { return Sub2.self }
else { fatalError("bad type code") }
}
class AnyBase: Codable {
let base: Base
init(_ b: Base) { base = b }
required init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let typeCode = try c.decode(String.self, forKey: .type)
/*if typeCode == "sub1" {
self.base = try c.decode(Sub1.self, forKey: .base)
} else if typeCode == "sub2" {
self.base = try c.decode(Sub2.self, forKey: .base)
} else {
fatalError("bad type code")
}*/
let typeObj = getTypeFromCode(typeCode)
self.base = try c.decode(typeObj, forKey: .base)
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(base.codingTypeKey, forKey: .type)
try c.encode(base, forKey: .base)
}
enum CodingKeys: CodingKey {
case base, type
}
}
// To to round-trip encode/decode and get the right object back...
let enc = JSONEncoder()
let dec = JSONDecoder()
let sub = Sub1()
let any = AnyBase(sub)
let data = try! enc.encode(any)
let str = String(data:data, encoding:.utf8)!
print(str)
let any2 = try! dec.decode(AnyBase.self, from: data)
print(type(of:any2.base))

Instead of getTypeFromCode (_:) method, you can create an enum BaseType like,
enum BaseType: String {
case sub1, sub2
var type: Base.Type {
switch self {
case .sub1: return Sub1.self
case .sub2: return Sub2.self
}
}
}
Now, in init(from:) get the BaseType using typeCode as rawValue, i.e.
class AnyBase: Codable {
required init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let typeCode = try c.decode(String.self, forKey: .type)
if let baseType = BaseType(rawValue: typeCode) {
self.base = try c.decode(baseType.type, forKey: .base)
} else {
fatalError("bad type code")
}
}
//rest of the code...
}

Related

Swift Recursively Encode a Custom Class Data Structure

I want to save a queue in UserDefault. When I decode the Queue from UserDefault, head and tail of the Queue are assigned by value which means they are two completely different objects and I can't enqueue through the tail. Is it possible to encode tail as a reference to head?
This is how class Queue is implemented
#State var RecentEmoji = Queue()
public class Node: Codable {
var value: Int
var next: Node?
init(value: Int) {
self.value = value
self.next = nil
}
enum CodingKeys: CodingKey {
case value, next
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
try container.encode(next, forKey: .next)
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
value = try container.decode(Int.self, forKey: .value)
next = try container.decode(Node?.self, forKey: .next)
}
}
public class Queue: Sequence, Codable {
fileprivate var head: Node?
private var tail: Node?
private var length: Int
init() {
head = nil
tail = nil
length = 0
}
enum CodingKeys: CodingKey {
case head, tail, length
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(head, forKey: .head)
try container.encode(tail, forKey: .tail)
try container.encode(length, forKey: .length)
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
head = try container.decode(Node?.self, forKey: .head)
tail = try container.decode(Node?.self, forKey: .tail)
length = try container.decode(Int.self, forKey: .length)
}
}
This is how I save the Queue to userDefault
let encoder = JSONEncoder()
do {
let encoded = try encoder.encode(RecentEmoji)
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: "RecentEmoji")
} catch {
print("\(error)")
}
And this is how I get them back
if let savedEmoji = UserDefaults.standard.value(forKey: "RecentEmoji") as? Data {
let decoder = JSONDecoder()
if let recentEmoji = try? decoder.decode(Queue.self, from: savedEmoji) {
RecentEmoji = recentEmoji
}
}

Save array of different object types in UserDefaults

I have two classes, Radio and Podcast, children of the Media class.
I'm trying to save an array of Media (with radios and podcasts) to UserDefaults but when I get it back, I only have medias (I'm losing information of Radio or Podcast).
I cannot cast the items to Radio or Podcast.
private func saveRecentMediaInData(_ medias:[Media]) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(medias) {
UserDefaults.standard.setValue(encoded, forKey: recentMediasKey)
}
}
private func getRecentMediasFromData() -> [Media] {
let defaults = UserDefaults.standard
if let data = defaults.value(forKey: recentMediasKey) as? Data {
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Array.self, from: data) as [Media] {
return decoded
}
}
return []
}
Thanks
The issue is not related to UserDefaults. It's having an array of mixed object to decode with Codable.
In this case, a solution is to use a enum with associated value:
enum Mixed: Codable {
case radio(Radio)
case podcast(Podcast)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let asRadio = try? container.decode(Radio.self) {
self = .radio(asRadio)
} else if let asPodcast = try? container.decode(Podcast.self) {
self = .podcast(asPodcast)
} else {
fatalError("Oops")
}
}
}
Here is a full sample code:
struct SubClassesCodable {
class Media: Codable, CustomStringConvertible {
var title: String
var description: String {
return "Media: \(title)"
}
}
class Radio: Media {
var channel: Int
enum CodingKeys: String, CodingKey {
case channel
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.channel = try container.decode(Int.self, forKey: .channel)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(channel, forKey: .channel)
}
override var description: String {
return "Radio: \(title) - \(channel)"
}
}
class Podcast: Media {
var author: String
enum CodingKeys: String, CodingKey {
case author
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.author = try container.decode(String.self, forKey: .author)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(author, forKey: .author)
}
override var description: String {
return "Podcast: \(title) - \(author)"
}
}
enum Mixed: Codable {
case radio(Radio)
case podcast(Podcast)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let asRadio = try? container.decode(Radio.self) {
self = .radio(asRadio)
} else if let asPodcast = try? container.decode(Podcast.self) {
self = .podcast(asPodcast)
} else {
fatalError("Oops") //Or rather throws a custom error
}
}
}
static func test() {
let mediaJSONStr = #"{"title": "media"}"#
let radioJSONStr = #"{"title": "radio", "channel": 3}"#
let podcastJSONStr = #"{"title": "podcast", "author": "myself"}"#
do {
let decoder = JSONDecoder()
//Create values from JSON
let media = try decoder.decode(Media.self, from: Data(mediaJSONStr.utf8))
print(media)
let radio = try decoder.decode(Radio.self, from: Data(radioJSONStr.utf8))
print(radio)
let podcast = try decoder.decode(Podcast.self, from: Data(podcastJSONStr.utf8))
print(podcast)
let array: [Media] = [radio, podcast]
print(array)
// Encode to Data, that's what's saved into UserDefaults
let encoder = JSONEncoder()
let encodedArray = try encoder.encode(array)
print("Encoded: \(String(data: encodedArray, encoding: .utf8)!)") //It's more readable as JSON String than Data
//This will fail, it's the current author code
let decoded = try decoder.decode([Media].self, from: encodedArray)
print(decoded)
decoded.forEach {
if let asRadio = $0 as? Radio {
print(asRadio)
}else if let asPodcast = $0 as? Podcast {
print(asPodcast)
} else {
print("Nop: \($0)")
}
}
//This is a working solution
let mixedDecoded = try decoder.decode([Mixed].self, from: encodedArray)
let decodedArray: [Media] = mixedDecoded.map {
switch $0 {
case .radio(let radio):
return radio
case .podcast(let podcast):
return podcast
}
}
print(decodedArray)
} catch {
print("Error: \(error)")
}
}
}
SubClassesCodable.test()

NSKeyedUnarchiver creates multiple instances of the same object references by others

I'm experimenting with NSKeyedArchiver because I'm looking into saving an object graph. However, there seems to be a problem with objects referencing the same instance of another object. Say, I have three classes: A, B and C that reference each other like this:
A --> B <-- C
A and C each have a reference to the same object B. When decoding this using NSKeyedUnarchiver, it simply creates multiple instances of B so that A and B do not reference the same object anymore.
Here's a full example:
import Foundation
class A: Codable {
var b: B
init(b: B) {
self.b = b
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.b = try container.decode(B.self, forKey: .b)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(b, forKey: .b)
}
private enum CodingKeys: String, CodingKey {
case b
}
}
class B: Codable {
init() {}
required init(from decoder: Decoder) throws {}
func encode(to encoder: Encoder) throws {}
}
class C: Codable {
var b: B
init(b: B) {
self.b = b
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.b = try container.decode(B.self, forKey: .b)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(b, forKey: .b)
}
private enum CodingKeys: String, CodingKey {
case b
}
}
class Store: Codable {
var a: A
var b: B
var c: C
init() {
b = B()
a = A(b: b)
c = C(b: b)
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.a = try container.decode(A.self, forKey: .a)
self.b = try container.decode(B.self, forKey: .b)
self.c = try container.decode(C.self, forKey: .c)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(a, forKey: .a)
try container.encode(b, forKey: .b)
try container.encode(c, forKey: .c)
}
private enum CodingKeys: String, CodingKey {
case a, b, c
}
}
let store = Store()
let archiver = NSKeyedArchiver(requiringSecureCoding: false)
try! archiver.encodeEncodable(store, forKey: NSKeyedArchiveRootObjectKey)
archiver.finishEncoding()
let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: archiver.encodedData)
if let decodedStore = try! unarchiver.decodeTopLevelDecodable(Store.self, forKey: NSKeyedArchiveRootObjectKey) {
// Will print false
print(decodedStore.a.b === decodedStore.c.b)
}
Am I doing something wrong or does something like this simply not work? Or is my example flawed?
Thanks!

Codable conformance for nested Enum?

I'm a bit tangled up on using Codable with nested enums. Suppose I have the following enum:
enum ItemStatus {
enum Foo {
case a
case b(Double, Double)
case c
}
enum Bar {
case x(String)
case y
case z(Int)
}
}
extension ItemStatus: Codable {
init(from decoder: Decoder) throws {
}
func encode(to encoder: Encoder) throws {
}
}
For normal enums, I'm implementing Codable like this. It works, but I'm not sure how to implement Codable for the top-level enum (in this case, ItemStats), and my gut tells me there is a more efficient way to write this anyway:
extension ItemStatus.Bar {
init?(rawValue: String?) {
guard let val = rawValue?.lowercased() else {
return nil
}
switch val {
case "x": self = .x("")
case "y": self = .y
case "z": self = .z(0)
default: return nil
}
}
private var typeStr: String {
guard let label = Mirror(reflecting: self).children.first?.label else {
return .init(describing: self)
}
return label
}
}
extension ItemStatus.Bar : Codable {
private enum CodingKeys: String, CodingKey {
case type
case xVal
case zVal
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
guard let type = try? container.decode(String.self, forKey: .type) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Could not get type of Bar."))
}
guard let base = ItemStatus.Bar(rawValue: type) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Could not init Bar with value: \(type)"))
}
switch base {
case .x:
let val = try container.decode(String.self, forKey: .xVal)
self = .x(val)
case .z:
let val = try container.decode(Int.self, forKey: .zVal)
self = .z(val)
default:
self = base
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.typeStr, forKey: .type)
switch self {
case .x(let val):
try container.encode(val, forKey: .xVal)
case .z(let val):
try container.encode(val, forKey: .zVal)
default: ()
}
}
}

How to parse JSON with Decodable protocol when property types might change from Int to String? [duplicate]

This question already has answers here:
Using codable with value that is sometimes an Int and other times a String
(5 answers)
Closed 6 months ago.
I have to decode a JSON with a big structure and a lot of nested arrays.
I have reproduced the structure in my UserModel file, and it works, except with one property (postcode) that is in a nested array (Location) that sometimes is an Int and some other is a String. I don't know how to handle this situation and tried a lot of different solutions.
The last one I've tried is from this blog https://agostini.tech/2017/11/12/swift-4-codable-in-real-life-part-2/
And it suggests using generics. But now I can't initialize the Location object without providing a Decoder():
Any help or any different approach would be appreciated.
The API call is this one: https://api.randomuser.me/?results=100&seed=xmoba
This is my UserModel File:
import Foundation
import UIKit
import ObjectMapper
struct PostModel: Equatable, Decodable{
static func ==(lhs: PostModel, rhs: PostModel) -> Bool {
if lhs.userId != rhs.userId {
return false
}
if lhs.id != rhs.id {
return false
}
if lhs.title != rhs.title {
return false
}
if lhs.body != rhs.body {
return false
}
return true
}
var userId : Int
var id : Int
var title : String
var body : String
enum key : CodingKey {
case userId
case id
case title
case body
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: key.self)
let userId = try container.decode(Int.self, forKey: .userId)
let id = try container.decode(Int.self, forKey: .id)
let title = try container.decode(String.self, forKey: .title)
let body = try container.decode(String.self, forKey: .body)
self.init(userId: userId, id: id, title: title, body: body)
}
init(userId : Int, id : Int, title : String, body : String) {
self.userId = userId
self.id = id
self.title = title
self.body = body
}
init?(map: Map){
self.id = 0
self.title = ""
self.body = ""
self.userId = 0
}
}
extension PostModel: Mappable {
mutating func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
body <- map["body"]
userId <- map["userId"]
}
}
Well it's a common IntOrString problem. You could just make your property type an enum that can handle either String or Int.
enum IntOrString: Codable {
case int(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .int(container.decode(Int.self))
} catch DecodingError.typeMismatch {
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(IntOrString.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload conflicts with expected type, (Int or String)"))
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let int):
try container.encode(int)
case .string(let string):
try container.encode(string)
}
}
}
As I have found mismatch of your model that you posted in your question and the one in the API endpoint you pointed to, I've created my own model and own JSON that needs to be decoded.
struct PostModel: Decodable {
let userId: Int
let id: Int
let title: String
let body: String
let postCode: IntOrString
// you don't need to implement init(from decoder: Decoder) throws
// because all the properties are already Decodable
}
Decoding when postCode is Int:
let jsonData = """
{
"userId": 123,
"id": 1,
"title": "Title",
"body": "Body",
"postCode": 9999
}
""".data(using: .utf8)!
do {
let postModel = try JSONDecoder().decode(PostModel.self, from: jsonData)
if case .int(let int) = postModel.postCode {
print(int) // prints 9999
} else if case .string(let string) = postModel.postCode {
print(string)
}
} catch {
print(error)
}
Decoding when postCode is String:
let jsonData = """
{
"userId": 123,
"id": 1,
"title": "Title",
"body": "Body",
"postCode": "9999"
}
""".data(using: .utf8)!
do {
let postModel = try JSONDecoder().decode(PostModel.self, from: jsonData)
if case .int(let int) = postModel.postCode {
print(int)
} else if case .string(let string) = postModel.postCode {
print(string) // prints "9999"
}
} catch {
print(error)
}
You can use generic like this:
enum Either<L, R> {
case left(L)
case right(R)
}
extension Either: Decodable where L: Decodable, R: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let left = try? container.decode(L.self) {
self = .left(left)
} else if let right = try? container.decode(R.self) {
self = .right(right)
} else {
throw DecodingError.typeMismatch(Either<L, R>.self, .init(codingPath: decoder.codingPath, debugDescription: "Expected either `\(L.self)` or `\(R.self)`"))
}
}
}
extension Either: Encodable where L: Encodable, R: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .left(left):
try container.encode(left)
case let .right(right):
try container.encode(right)
}
}
}
And then declare postcode: Either<Int, String> and if your model is Decodable and all other fields are Decodable too no extra code would be needed.
If postcode can be both String and Int, you have (at least) two possible solutions for this issue. Firstly, you can simply store all postcodes as String, since all Ints can be converted to String. This seems like the best solution, since it seems highly unlikely that you'd need to perform any numeric operations on a postcode, especially if some postcodes can be String. The other solution would be creating two properties for postcode, one of type String? and one of type Int? and always only populating one of the two depending on the input data, as explained in Using codable with key that is sometimes an Int and other times a String.
The solution storing all postcodes as String:
struct PostModel: Equatable, Decodable {
static func ==(lhs: PostModel, rhs: PostModel) -> Bool {
return lhs.userId == rhs.userId && lhs.id == rhs.id && lhs.title == rhs.title && lhs.body == rhs.body
}
var userId: Int
var id: Int
var title: String
var body: String
var postcode: String
enum CodingKeys: String, CodingKey {
case userId, id, title, body, postcode
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.userId = try container.decode(Int.self, forKey: .userId)
self.id = try container.decode(Int.self, forKey: .id)
self.title = try container.decode(String.self, forKey: .title)
self.body = try container.decode(String.self, forKey: .body)
if let postcode = try? container.decode(String.self, forKey: .postcode) {
self.postcode = postcode
} else {
let numericPostcode = try container.decode(Int.self, forKey: .postcode)
self.postcode = "\(numericPostcode)"
}
}
}
try this extension
extension KeyedDecodingContainer{
public func decodeIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> String?{
if let resStr = try? decode(type, forKey: key){
return resStr
}else{
if let resInt = try? decode(Int.self, forKey: key){
return String(resInt)
}
return nil
}
}
public func decodeIfPresent(_ type: Int.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> Int?{
if let resInt = try? decode(type, forKey: key){
return resInt
}else{
if let resStr = try? decode(String.self, forKey: key){
return Int(resStr)
}
return nil
}
}
}
example
struct Foo:Codable{
let strValue:String?
let intValue:Int?
}
let data = """
{
"strValue": 1,
"intValue": "1"
}
""".data(using: .utf8)
print(try? JSONDecoder().decode(Foo.self, from: data!))
it will print "Foo(strValue: Optional("1"), intValue: Optional(1))"