I'm getting variables of Struct as [Key:Value]
inside an array by using Mirror
. Mirror returns variables in a sorted order. However, after they are set on array, sort spoils. How can I protect the sort? I try to sort array after set with reference of Mirror.children
but can't figure out.
for loop inside function returns a correct and sorted value. Problem is after they are set on result[property] = value
, sort spoils. How can I protect the sort?
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
}
//let sorted = result.sorted{ mirror.children.index(of: $0.key)! < mirror.children.index(of: $1.key)! } TRYING THIS
return result
}
}