0
votes

I have a struct which consist of some elements which are in String, Bool and Int lets call it Struct A. I also have an another struct lets called it Struct B.

Struct A{
let name: String
let surname: String
let age: Int   
}

Struct B{
let columnId: Int
let value: String
}

I have an array of B and I want to assign values of A to B. Example array;

FirstElement(columnId:1,value:"name=myname") SecondElement(columnId:2,value:"surname=mysurname") ThirdElement(columnId:3,value:"age=20")

I can get all properties of a struct with below extension;

extension Loopable {
func allProperties() throws -> [String: Any] {

    var result: [String: Any] = [:]

    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, value) in mirror.children {
        guard let property = property else {
            continue
        }

        result[property] = value
    }

    return result
}
}

After I get the all properties I want some kind of iteration; My question is that how can I get value and key like "value=key" string in below "classA[i]"

 func setArray(){
 let classA = classA().getAllProperties()
    for i in 0..<deviceLogs.count{
        myArray.append(B(columnId: i, value: classA[i]) )
    }
}

EDIT: I want to get all the properties with its values inside Struct A and use it as String for value property when creating Struct B object.

2
classA["name"] is not working?Retterdesdialogs
If you have to use Mirror, you are doing something wrong.Sulthan

2 Answers

1
votes

Modify your setArray function

func setArray(){
    let keysArray = Array(classA.keys)
    let valuesArray = Array(classA.values)

    let classA = classA().getAllProperties()
    for i in 0..<deviceLogs.count{
        let valueString = keysArray[i] + "=" + valuesArray[i]
        myArray.append(B(columnId: i, value: valueString) )
    }
}
1
votes

Check out this

struct B {
    let columnId: Int
    let value: Any
}

protocol Properties {
    var allProperties: [Any] { get }
}

extension Properties {
    var allProperties: [Any] {
        return Mirror(reflecting: self).children.flatMap { $0 }
    }
}    

struct A: Properties {
    let name: String
    let surname: String
    let age: Int
}

Here is the example how you can use it:

let properties = A(name: "name", surname: "surname", age: 18).allProperties

// NOTE: your value property in B should be of type Any in place of String

var list = [B]()
for (index, property) in properties.enumerated() {
    list.append(B(columnId: index, value: property))
}