Jimmery
Jimmery

Reputation: 10139

Accessing the properties of an object with a string in Swift

In Javascript I can reference properties of an object like this:

obj.prop

Or like this:

obj["prop"]

Is there a similar method in Swift of accessing the properties of an object with a string?

Upvotes: 1

Views: 67

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

There is no way to do it that would work for any Swift class. However, you can do this:

class User: NSObject {
    dynamic var username: String = "admin"
    dynamic var password: String = "123456"
}

let u = User()
u.valueForKey("username") // admin

This works if:

  • You adopt the NSObject protocol;
  • You define your vars as dynamic.

Upvotes: 2

Related Questions