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

后端 未结 3 2119
南方客
南方客 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:14

    You wouldn't access a struct property by name in Swift any more than you would in C++. You'd provide a block.

    Extemporaneous:

    func calculateAverage(getter: (Data) -> Double) {
        ... total += getter(data) ...
    }
    
    ...
    
    calculateAverage({$0.old})
    calculateAverage({$0.new})
    

    Possibly with average {$0.old} being a more natural syntax — the verb isn't really helpful and if you're asserting what it is, not what the computer should do, then omitting the brackets looks fine.

提交回复
热议问题