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:
clas
Shim's answer above doesn't work anymore in Swift 4. There are two things you should be aware of.
First of all, if you want to use value(forKey:)
function, your class must inherit NSObject
.
Secondly, since Objective-C doesn't know anything about value type, you have to put the @objc
keyword in front of your value type properties and Swift will do the heavy-lifting for you.
Here is the example:
import Foundation
class Person: NSObject {
@objc var name: String = "John Dow"
@objc var age: Int = 25
@objc var height: Int = 180
subscript(key: String) -> Any? {
return self.value(forKey: key)
}
}
let person: Person = Person()
person["name"] // "John Dow"
person["age"] // 25
person["height"] // 180