swift. 扩展类添加属性_Swift iOS-如何动态地向现有类添加属性然后访问它们
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() -> ??? {
}
}
解決方案
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)
}
總結
以上是生活随笔為你收集整理的swift. 扩展类添加属性_Swift iOS-如何动态地向现有类添加属性然后访问它们的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python控制语句第一章_【原创】Py
- 下一篇: python自动投递简历_python模