
在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_nameprint($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 }}解决方法 你可以做到,但不能使用“纯粹的”Swift. Swift(作为一种语言)的重点是防止这种危险的动态属性访问.你必须使用Cocoa的 Key-Value Coding功能: self.setValue(value,forKey:fIEld)
非常方便,它完全穿过你要穿过的字符串到属性名称的桥,但要注意:这里是龙.
(但如果可能的话,最好将您的架构重新实现为字典.字典具有任意字符串键和相应的值,因此没有桥可以交叉.)
总结以上是内存溢出为你收集整理的ios – 如何从变量访问属性或方法?全部内容,希望文章能够帮你解决ios – 如何从变量访问属性或方法?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)