本文介绍了Swift iOS-如何动态地向现有类添加属性然后访问它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要向现有类动态添加属性,然后访问它们。我使用 objc_setAssociatedObject
找到了,但是没有上下文用它。我该如何实现?
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() -> ??? {
}
}
推荐答案
在评论中使用@DonMag的建议,他给了我一个很好的选择。他建议我创建一个字典作为类的属性,然后将键,值对添加到它。
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)
}
}
}
}
要使用它:
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 iOS-如何动态地向现有类添加属性然后访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!