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

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

    You're looking for key-value-coding (KVC) that is accessing properties by key (path).

    Short answer: A struct does not support KVC.

    If the struct is not mandatory in your design use a subclass of NSObject there you get KVC and even operators like @avg for free.

    class MyData : NSObject {
      @objc let old, new: Double
    
      init(old:Double, new:Double) {
        self.old = old
        self.new = new
      }
    }
    
    let myDataArray : NSArray = [MyData(old: 1, new: 3), MyData(old:5, new: 9), MyData(old: 12, new: 66)]
    
    let averageOld = myDataArray.value(forKeyPath:"@avg.old")
    let averageNew = myDataArray.value(forKeyPath: "@avg.new")
    

    Edit: In Swift 4 a struct does support Swift KVC but the operator @avg is not available

提交回复
热议问题