Search code examples
swiftkey-value-coding

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

Solution

  • This is Key-Value Coding:

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