是否可以使用變量作爲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