Is there a simple way to iterate over all of the properties of a struct? The approach for non-static properties that I am familiar with is using Mirror, but this returns an empty array when the struct contains only static properties. Here's an example of what I am trying to achieve:
struct Tree {
static let bark = "Bark"
static let roots = "Roots"
}
let treeParts = [String]()
// insert code here to make treeParts = ["Bark", "Roots"]
Since I also have an interest of how to do this I made the example below. Why not just create the struct with non static properties plus a static instance variable which makes the struct a singleton. The following code sample details an example use case for mapping values of a
Person
object to a JSON dictionary using the REST API's naming semantics. The property names ofPersonJSONKeys
have to match the property names ofPerson
.The code for the
allProperties()
function comes from How to loop over struct properties in Swift?. You can modify this function easily to only return the values of a structs properties.Since the Struct is now a singleton all of its properties will be initialised only once and the thread safety is given by its static instance variable.