Hey everyone,
I have a couple of classes and some of them (but not all of them) are indistinguishable from one another. All of the classes share the same base class. And all of the classes implement an empty protocol:
protocol MyDecodable: AnyObject, Codable {}
class MyBaseClass: MyDecodable {
var identifier: UUID {
UUID()
}
}
class MyClassOne: MyBaseClass {
var myString: String?
var myStrings: [String] = [String]()
}
class MyClassTwo: MyBaseClass {
var myString: String?
var myStrings: [String] = [String]()
}
class MyClassThree: MyBaseClass {
let myString: String
let myInts: [Int]
init(myString: String, myInts: [Int]) {
self.myString = myString
self.myInts = myInts
super.init()
}
enum MyClassThreeKeys: CodingKey {
case myString, myInts
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: MyClassThreeKeys.self)
self.myString = try container.decode(String.self, forKey: .myString)
self.myInts = try container.decode([Int].self, forKey: .myInts)
try super.init(from: decoder)
}
}
I notice that when I have some data which can be decoded, I am having trouble with the objects once they are initialized:
func test_MyClasses() throws {
var dict = [String: Any]()
let firstObj = MyClassOne()
firstObj.myString = "firstObjProp"
firstObj.myStrings = ["firstObjProp", "sasdasf", "asdasdasdasd", "adsasdasdasdasdasd"]
let encoder = JSONEncoder()
let data = try encoder.encode(firstObj)
let decoder = JSONDecoder()
var count: UInt32 = 0
let classListPtr = objc_copyClassList(&count)
UnsafeBufferPointer(
start: classListPtr, count: Int(count)
).compactMap({
if let cod = $0 as? MyDecodable.Type {
do {
let result = try decoder.decode(cod, from: data)
if let description = (result as AnyObject).description?.components(separatedBy: ".").last {
dict[description] = result
}
} catch {
//print(error)
}
}
})
print(dict.description)
}
}
I am seeing that inside of dict
I have an object of each class type, MyClassOne
and MyClassTwo
as well as MyBaseClass
. Having these objects makes sense because the data
from encoding MyClassOne
should be able to be decoded as either of the other two.
However, the properties are empty. It seems like the properties are not being initialized with the object.
Can you help me figure out what I have overlooked? I was expecting that I can have my properties set from decoding the data.
Note:
It kind of looks like the synthesized initializer that is being chosen (during the decoding) is the one that corresponds with init()
rather than init(myString: String, myStrings:[String])
.. Would that be the expected behavior for this scenario?