Access a struct property by its name as a string in Swift

后端 未结 3 2118
南方客
南方客 2021-02-20 13:28

Let\'s say I have the following struct in Swift:

struct Data {
   let old: Double
   let new: Double
}

Now I have a c

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 14:11

    What about this "reflection-less" solution?

    struct Data {
        let old: Double
        let new: Double
    
        func valueByPropertyName(name:String) -> Double {
            switch name {
            case "old": return old
            case "new": return new
            default: fatalError("Wrong property name")
            }
        }
    }
    

    Now you can do this

    let data = Data(old: 0, new: 1)
    
    data.valueByPropertyName("old") // 0
    data.valueByPropertyName("new") // 1
    

提交回复
热议问题