1

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() -> ??? {

     }
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
  • 3
    Do you really want to add dynamic properties? Instead, you could add a dictionary as a property, and then simply add key/value pairs to that dictionary. – DonMag Jan 17 '19 at 16:52
  • @DonMag that's actually a good idea. I just tried it and it's working. You can post it as an answer and I'll accept it. Thanks :) – Lance Samaria Jan 17 '19 at 17:09
  • @DonMag I posted an answer for now. If you post I'll delete mines and accept yours. Thanks for the help :) – Lance Samaria Jan 17 '19 at 17:26

1 Answers1

2

Using the suggestion from @DonMag in the comments he gave me a great alternative. He suggested I create a dictionary as a property on the class then add the key,value pairs to it.

class Order {

    var orderId: String?

    var dynamicDict = [String: Any]()

    convenience init(dict: [String: Any]) {
        self.init()

        orderId = dict["orderId"] as? String

        createDynamicKeyValues(dict: dict)
    }

    func createDynamicKeyValues(dict: [String: Any]) {

        for (key, value) in dict {

            if key.contains("+") {

                dynamicDict.updateValue(value, forKey: key)
            }
        }
    }
}

To use it:

let dict = ["orderId":"abc", "postId+0":"zero", "postId+1":"one", "postId+2":"two"] // postIds can go on

let order = Order(dict: dict)

for (key, value) in order.dynamicDict {
    print(key)
    print(value)
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256