是否可以使用变量作为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
}
}
这就是我在寻找和试图做之前张贴在这里。但是,我忘了将NSObject扩展到我的类,因此没有得到.setValue()选项。我在这篇文章之前也在考虑@ bluedome的回答,但是,我在这堂课中有大约30个属性,并且正在寻找避免下标中硬编码的方法。 – balatin 2014-12-22 19:52:38
+1作为字典建议的实现体系结构。非常好的问题是要问自己,这是纯数据问题还是真的需要跨越动态语言线 – bitwit 2016-01-06 17:03:42