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.
Mirror
, you are doing something wrong. – Sulthan