我在Swift中有一个自定义类,我想使用下标访问其属性,这可能吗?
我想要的是这样的:
class User {
var name: String
var title: String
subscript(key: String) -> String {
// Something here
return // Return the property that matches the key…
}
init(name: String, title: String) {
self.name = name
self.title = title
}
}
myUser = User(name: "Bob", title: "Superboss")
myUser["name"] // "Bob"
更新:之所以要这样做,是因为我正在使用GRMustache从HTML模板进行渲染。我希望能够将我的模型对象传递给GRMustache渲染器…
GRMustache使用带键的下标objectForKeyedSubscript:方法和键值编码的valueForKey:方法来获取值。任何符合条件的对象都可以为模板提供值。
https://github.com/groue/GRMustache/blob/master/Guides/view_model.md#viewmodel-objects
(此处为GRMustache作者)
在面向Swift的Mustache库发布之前,我建议您从NSObject继承类(以便它们具有valueForKey:
方法)。然后,GRMustache将使用此方法获取值。
如果仍然无法使用(渲染中的空白值),则可以尝试禁用GRMustache安全功能(请参阅https://github.com/groue/GRMustache/blob/master/Guides/security.md#disabling-safe -key-access)
如果您遇到任何其他麻烦,请直接在存储库中打开一个问题:https : //github.com/groue/GRMustache/issues
编辑2015年2月2日:GRMustache.swift已发布:http ://github.com/groue/GRMustache.swift
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句