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 レンダラーに渡すだけにしたいのですが…</p>
GRMustache は、キー付き添字 objectForKeyedSubscript: メソッドとキー値コーディング valueForKey: メソッドを使用して値をフェッチします。準拠オブジェクトは、テンプレートに値を提供できます。
https://github.com/groue/GRMustache/blob/master/Guides/view_model.md#viewmodel-objects