在 Swift 中通过下标访问属性 [英] Access properties via subscripting in Swift

查看:30
本文介绍了在 Swift 中通过下标访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 中有一个自定义类,我想使用下标来访问它的属性,这可能吗?

I have a custom class in Swift and I'd like to use subscripting to access its properties, is this possible?

我想要的是这样的:

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 渲染器......

Update: The reason why I'm looking for this is that I'm using GRMustache to render from HTML templates. I'd like to be able to just pass my model object to the GRMustache renderer…

GRMustache 使用键控下标 objectForKeyedSubscript: 方法和键值编码 valueForKey: 方法获取值.任何合规对象都可以为模板提供值.

GRMustache fetches values with the keyed subscripting objectForKeyedSubscript: method and the Key-Value Coding valueForKey: method. Any compliant object can provide values to templates.

https://github.com/groue/GRMustache/blob/master/Guides/view_model.md#viewmodel-objects

推荐答案

(GRMustache 作者在这里)

(GRMustache author here)

在面向 swift 的 Mustache 库问世之前,我建议让您的类从 NSObject 继承(以便它们具有 valueForKey: 方法).然后 GRMustache 将使用此方法获取值.

Until a swift-oriented Mustache library is out, I suggest having your classes inherit from NSObject (so that they have the valueForKey: method). GRMustache will then fetch values with this method.

如果这仍然不起作用(渲染中的空白值),您可以尝试禁用 GRMustache 安全功能(请参阅 https://github.com/groue/GRMustache/blob/master/Guides/security.md#disabling-safe-key-access)

In case this would still not work (blank values in the rendering), you may try to disable GRMustache security features (see https://github.com/groue/GRMustache/blob/master/Guides/security.md#disabling-safe-key-access)

如果您遇到任何其他问题,请直接在存储库中打开一个问题:https://github.com/groue/GRMustache/issues

Should you experience any other trouble, please open an issue right into the repository: https://github.com/groue/GRMustache/issues

编辑 2015 年 2 月 2 日:GRMustache.swift 已发布:http://github.com/groue/GRMustache.swift

EDIT February 2, 2015: GRMustache.swift is out: http://github.com/groue/GRMustache.swift

这篇关于在 Swift 中通过下标访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆