Access properties via subscripting in Swift

后端 未结 6 1623
情歌与酒
情歌与酒 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条回答
  •  梦毁少年i
    2021-01-04 01:09

    Using valueForKey should enable you to access properties using their names. Be sure that you're working with a object that inherit NSObject

    class people: NSObject {
        var age: NSString = "44"
        var height: NSString = "153"
    }
    
    let person:people = people()
    
    let stringVariable = "age"
    
    person.valueForKey("age")
    // Print "44"
    
    person.valueForKey("\(stringVariable)")
    // Print "44"
    

提交回复
热议问题