Search code examples
swiftswift-playground

Access properties via subscripting in Swift


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

What I want is something like this:

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"

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 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


Solution

  • (GRMustache author here)

    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.

    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)

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

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