struct Person : Encodable {
var name: String
var age: Int
var address: String?
}
let person = Person(name: "John Smith", age: 30, address: nil)
let dictionary = person.toDictionary()
print(dictionary) // Output: ["name": "John Smith", "age": 30]
extension Encodable {
func toDictionary() -> [String: Any]? {
let mirror = Mirror(reflecting: self)
var dictionary = [String: Any]()
for child in mirror.children {
guard let label = child.label else {
continue
}
dictionary[label] = child.value
}
return dictionary
}
}