I need to dynamically add properties to an existing class then access them. I found this answer using objc_setAssociatedObject
but there’s no context on how to use it. How can I achieve this?
let dict = ["orderId":"abc", "postId+0":"zero", "postId+1":"one", "postId+2":"two"] // postIds can go on
let order = Order(dict: dict)
let dynamicProperties = order.accessDynamicProperties()
print(dynamicProperties)
Class:
class Order {
var orderId: String?
// I have a main initilizer that I use for something else that's why I'm using a convenience init
convenience init(dict: [String: Any]) {
self.init()
orderId = dict["orderId"] as? String
dynamicallyCreateProperties(dict: dict)
}
func dynamicallyCreateProperties(dict: [String: Any]) {
for (key, value) in dict {
if key.contains("+") {
// dynamically add property and value to class
}
}
}
// returns something???
func accessDynamicProperties() -> ??? {
}
}