Access properties via subscripting in Swift

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

    I suppose you could do:

    class User {
        let properties = Dictionary()
    
        subscript(key: String) -> String? {
            return properties[key]
        }
    
        init(name: String, title: String) {
            properties["name"] = name
            properties["title"] = title
        }
    }
    

    Without knowing your use case I would strongly advise against doing this.

    Another approach:

    class User {
        var name : String
        var title : String
    
        subscript(key: String) -> String? {
            switch key {
                case "name" : return name
                case "title" : return title
                default : return nil
            }
        }
    
        init(name: String, title: String) {
            self.name = name
            self.title = title
        }
    }
    

    It might be worth noting that Swift doesn't appear to currently support reflection by names. The reflect function returns a Mirror whose subscript is Int based, not String based.

提交回复
热议问题