Loop through Swift struct to get keys and values

use following code to get array of all the properties

protocol PropertyLoopable
{
    func allProperties() throws -> [String]
}

extension PropertyLoopable {
    func allProperties() throws -> [String] {

        var result: [String] = []

        let mirror = Mirror(reflecting: self)

        // Optional check to make sure we're iterating over a struct or class
        guard let style = mirror.displayStyle, style == .struct || style == .class else {
            throw NSError()
        }

        for (property,_) in mirror.children {
            guard let property = property else {
                continue
            }
            result.append(property)
         //   result[property] = value
        }

        return result
    }
}

Now just

let allKeys = try  self.allProperties()

Don't forgot to implement protocol

Hope it is helpful


First of all let's use CamelCase for the struct name

struct MyStruct {
    var a = "11215"
    var b = "21212"
    var c = "39932"
}

Next we need to create a value of type MyStruct

let elm = MyStruct()

Now we can build a Mirror value based on the elm value.

let mirror = Mirror(reflecting: elm)

The Mirror value does allow us to access all the properties of elm, here's how

for child in mirror.children  {
    print("key: \(child.label), value: \(child.value)")
}

Result:

key: Optional("a"), value: 11215

key: Optional("b"), value: 21212

key: Optional("c"), value: 39932

Tags:

Struct

Swift