我需要向现有类动态添加属性,然后访问它们。我发现this answer是使用objc_setAssociatedObject
的,但没有关于如何使用它的上下文。我该如何实现?
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 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() -> ??? {
}
}
答案 0 :(得分:1)
在评论中使用@DonMag的建议,他给了我一个很好的选择。他建议我创建一个字典作为类的一个属性,然后向其中添加键,值对。
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)
}
}
}
}
要使用它:
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)
}