如何从变量访问属性或方法?

bal*_*tin 9 ios swift

是否可以使用变量作为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"
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 8

你可以做到,但不能使用"纯粹的"Swift.Swift(作为一种语言)的重点是防止这种危险的动态属性访问.您必须使用Cocoa的键值编码功能:

self.setValue(value, forKey:field)
Run Code Online (Sandbox Code Playgroud)

非常方便,它完全穿过你要穿过的字符串到属性名称桥,但要注意:这里是龙.

(但如果可能的话,最好将您的架构重新实现为字典.字典具有任意字符串键和相应的值,因此没有桥可以交叉.)


blu*_*ome 8

订阅可能对您有所帮助.

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        
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)