在Swift中以字符串的形式通过结构名称访问结构属性 [英] Access a struct property by its name as a string in Swift

查看:89
本文介绍了在Swift中以字符串的形式通过结构名称访问结构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Swift中具有以下struct:

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

现在我有一个带有数据结构数组的类:

Now I have a class with an array of Data structs:

class MyClass {
   var myDataArray: [Data]
}

现在假设我要计算旧值或新值的平均值:

Now let's say I want to calculate the average of either the old or the new values:

func calculateAverage(oldOrNew: String) -> Double {
   var total = 0.0
   count = 0

   for data in myDataArray {
      total += data.oldOrNew
      count++
   }

   return total / Double(count)
}

然后:

let oldAverage = calculateAverage("old")
let newAverage = calculateAverage("new")

但这显然不起作用,因为oldOrNew不是我的struct的成员.

But this obviously doesn't work, since oldOrNew is not a member of my struct.

如何从"old""new"访问oldnew?

推荐答案

这种无反射"解决方案呢?

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")
        }
    }
}

现在您可以这样做

let data = Data(old: 0, new: 1)

data.valueByPropertyName("old") // 0
data.valueByPropertyName("new") // 1

这篇关于在Swift中以字符串的形式通过结构名称访问结构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆