从string - swift获取struct属性

时间:2018-01-27 15:12:31

标签: arrays swift struct

我声明了一个包含4个属性的结构( informationA,informationB,informationC,informationD )。

此外,我已经声明了这样的数组(该数组包含my_struct属性的一些名称为"strings"

let keys = ["informationA", "informationB", "informationC"]

现在,我希望for循环通过"keys"-arrayprint out the struct property values获取当前字符串(“informationA”,“informationB”,“informationC” )。

struct my_struct {
    var informationA = "test"
    var informationB = "test...test"
    var informationC = "test...test"
    var informationD = "test...test..."
}



func getInformation() {
   let keys = ["informationA", "informationB", "informationC"]
   for i in keys {
       print(my_struct.i) // ERROR: Type 'my_struct' has no member 'i'

      // should print ---> "test", "test...test", "test...test"
   }
}

使用上面的代码我收到此错误ERROR: Type 'my_struct' has no member 'i'。 有没有办法避免这个消息,并达到我想要的结果?

1 个答案:

答案 0 :(得分:3)

您正在寻找的是反思:

struct MyStruct {
    var informationA = "test"
    var informationB = "test...test"
    var informationC = "test...test"
    var informationD = "test...test..."
}

func getInformation() {
    let my_struct = MyStruct()
    let keys = ["informationA", "informationB", "informationC"]
    let m = Mirror(reflecting: my_struct)
    let properties = Array(m.children)

    for k in keys {
        if let prop = properties.first(where: { $0.label == k }) {
            print(prop.value)
        }
    }
}