【问题标题】:How to access property or method from a variable?如何从变量访问属性或方法?
【发布时间】:2017-12-01 22:22:25
【问题描述】:

是否可以在 Swift 中使用变量作为方法或属性的名称来访问方法或属性?

在 PHP 中,您可以使用 $object->{$variable}。例如

class Object {
  public $first_name;
}

$object = new Object();
$object->first_name = 'John Doe';

$variable = 'first_name';
$first_name = $object->{$variable}; // Here we can encapsulate the variable in {} to get the value first_name
print($first_name);
// Outputs "John Doe"

编辑:

这是我正在使用的实际代码:

class Punchlist {
    var nid: String?
    var title: String?

    init(nid: String) {

        let (result, err) = SD.executeQuery("SELECT * FROM punchlists WHERE nid = \(nid)")
        if err != nil {
            println("Error")
        }
        else {
            let keys = self.getKeys()  // Get a list of all the class properties (in this case only returns array containing "nid" and "title")
            for row in result {  // Loop through each row of the query
                for field in keys {  // Loop through each property ("nid" and "title")
                    // field = "nid" or "title"
                    if let value: String = row[field]?.asString() {
                        // value = value pulled from column "nid" or "title" for this row
                        self.field = value  //<---!! Error: 'Punchlist' does not have a member named 'field'
                    }
                }
            }
        }
    }

    //  Returns array of all class properties
    func getKeys() -> Array<String> {
        let mirror = reflect(self)
        var keys = [String]()
        for i in 0..<mirror.count {
            let (name,_) = mirror[i]
            keys.append(name)
        }

        return keys
    }
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    下标可能会对您有所帮助。

    let punch = Punchlist()
    punch["nid"] = "123"
    println(punch["nid"])
    
    class Punchlist {
        var nid: String?
        var title: String?
    
        subscript(key: String) -> String? {
            get {
                if key == "nid" {
                    return nid
                } else if key == "title" {
                    return title
                }
                return nil
            }
            set {
                if key == "nid" {
                    nid = newValue
                } else if key == "title" {
                    title = newValue        
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      你可以做到,但不能使用“纯”Swift。 Swift(作为一种语言)的全部意义在于防止那种危险的动态属性访问。您必须使用 Cocoa 的 Key-Value Coding 功能:

      self.setValue(value, forKey:field)
      

      非常方便,它恰好穿过了您想要穿过的字符串到属性名称的桥梁,但要注意:这里是龙。

      (但如果可能,最好将架构重新实现为字典。字典具有任意字符串键和对应值,因此没有可跨越的桥梁。)

      【讨论】:

      • 这是我在发帖之前一直在寻找并尝试做的事情。但是,我忘记将 NSObject 扩展到我的班级,因此没有获得 .setValue() 选项。在这篇文章之前,我也在考虑@bluedome 的答案,但是,我在这个类中有大约 30 个属性,并且正在寻找一种方法来避免下标中的硬编码。
      • +1 用于实现架构作为字典建议。很好的问题是问自己这是纯数据问题还是您真的需要跨越动态语言界限
      猜你喜欢
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2019-08-05
      相关资源
      最近更新 更多