我声明了一个包含4个属性的结构( informationA,informationB,informationC,informationD )。
此外,我已经声明了这样的数组(该数组包含my_struct属性的一些名称为"strings"
:
let keys = ["informationA", "informationB", "informationC"]
现在,我希望for循环通过"keys"-array
和print 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'
。
有没有办法避免这个消息,并达到我想要的结果?
答案 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)
}
}
}