Using Mirror type in Swift to convert Struct into a dictionary

In Swift, you can convert a struct into a dictionary by using the Mirror type, which provides a way to introspect the values of an instance of a struct or class.

Here’s an example of how you can convert a struct into a dictionary:

struct Person {
    let name: String
    let age: Int
    let email: String

let person = Person(name: "John", age: 30, email: "")

let mirror = Mirror(reflecting: person)

var dictionary = [String: Any]()

for child in mirror.children {
    guard let key = child.label else { continue }
    dictionary[key] = child.value

print(dictionary) // Output: ["name": "John", "age": 30, "email": ""]

In this example, we create a Person struct with three properties: name, age, and email. Then we create a Mirror instance using the reflecting initializer, which takes the struct as a parameter.

We then create an empty dictionary with a string key and an Any value. We iterate over the Mirror instance’s children using a for loop, and for each child, we check if it has a label (which is the property name). If it does, we add the label and value to the dictionary.

Finally, we print out the dictionary to verify that the struct has been successfully converted.



Leave a Reply

Your email address will not be published. Required fields are marked *