我想通过使用等于变量名的字符串来针对类中的变量(属性)。有办法吗?
class Person {
let name: String
let email: String
let address: String
let propertiesMap: [String : String] = [
"person_name": "name",
"person_email_address": "email"
]
init(_ data: NSDictionary) {
for element in data {
# string key address of Person property
propertiesMap[ element.key ]
# value to be assigned to the property
element.value
}
}
}
我希望遍历数据NSDictionary,如果字典的键与类的属性匹配,则将数据NSDictionary中的键的值分配给class属性
答案 0 :(得分:0)
一种方法可能是
class Person: NSObject{
@objc var name: String?
@objc var email: String?
class func from(dict: [String:String]) -> Person{
let v = Person()
for element in dict{
v.setValue(element.value, forKey: element.key)
}
return v
}
}
func test(){
let p = Person.from(dict: ["name":"John","email":"john@doe.com"])
print("name \(p.name ?? ""), email \(p.email ?? "")")
}