Access properties via subscripting in Swift

后端 未结 6 1588
情歌与酒
情歌与酒 2021-01-04 00:43

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         


        
6条回答
  •  一整个雨季
    2021-01-04 00:58

    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
    

提交回复
热议问题