danielavila
danielavila

Reputation: 144

Get instance attributes dynamically Swift 3

I'm trying to figure out a way to set/get the attributes of an instance of a class dynamically.

User class:

class User: NSObject {
    var email: String = ""
    var password: String = ""
}

I'm trying to set/get attributes something like this, (I know that .send() does not exists but I'm trying to find something like that if it's possible)

var user = User()
// Set
user.send('email') = "[email protected]"
// Get
print(user.send('email'))

Upvotes: 1

Views: 896

Answers (1)

Rob Napier
Rob Napier

Reputation: 299425

This is Key-Value Coding:

user.setValue("[email protected]", forKey:"email")
print(user.value(forKey:"email"))

Upvotes: 3

Related Questions