如何使用与变量名称匹配的字符串访问变量并为变量赋值

时间:2019-06-25 11:01:14

标签: swift string variables

我想通过使用等于变量名的字符串来针对类中的变量(属性)。有办法吗?

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属性

1 个答案:

答案 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 ?? "")")
}