Preview:
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
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter