Access properties via subscripting in Swift

后端 未结 6 1633
情歌与酒
情歌与酒 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 01:07

    This is a bit of a hack using reflection. Something along the lines of the following could be used.

    protocol PropertyReflectable { }
    
    extension PropertyReflectable {
        subscript(key: String) -> Any? {
            let m = Mirror(reflecting: self)
            for child in m.children {
                if child.label == key { return child.value }
            }
            return nil
        }
    }
    
    struct Person {
        let name: String
        let age: Int
    }
    
    extension Person : PropertyReflectable {}
    

    Then create a Person and access it's keyed properties.

    let p = Person(name: "John Doe", age: 18)
    
    p["name"] // gives "John Doe"
    p["age"] // gives 18
    

    You could modify the subscript to always return an interpolated string of the property value.

提交回复
热议问题