Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get struct properties from string - swift

I declared a struct with 4 properties ( informationA, informationB, informationC, informationD ).

Also I've declared an array like this (The array includes some names of the my_struct properties as "strings" :

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

Now I'd like a for-loop to go through the "keys"-array and print out the struct property values for the current string ("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"
   }
}

Using the code from above I'm getting this error ERROR: Type 'my_struct' has no member 'i'. Is there a way to avoid this message and achieve the result I'd like to get?

like image 566
Jonas0000 Avatar asked Sep 17 '25 01:09

Jonas0000


1 Answers

What you are looking for is reflection:

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)
        }
    }
}
like image 122
Code Different Avatar answered Sep 19 '25 09:09

Code Different