Snippets Collections
extension Encodable {
    func toDictionary() -> [String: Any]? {
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(self)
            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            return dictionary
        } catch {
            print("Error converting to dictionary:", error)
            return nil
        }
    }
}
Make sure to add encodable like this 

struct modelName : Encodsble

let categories = categoriesArray.map{ $0.toDictionary()  }

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
    }
}
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
    }
}
 
def merge_two_dicts(a, b):
 
 
   c = a.copy()   # make a copy of a
 
   c.update(b)    # modify keys and values of a with the ones from b
 
   return c
 
 
 
 
 
a = { 'x': 1, 'y': 2}
 
b = { 'y': 3, 'z': 4}
 
 
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
 
 
star

Fri Jun 23 2023 08:10:31 GMT+0000 (Coordinated Universal Time)

#ios #swift #dic #dict #model #modelarray #dictonary
star

Fri Mar 31 2023 06:42:39 GMT+0000 (Coordinated Universal Time)

#ios #swift #dict #model #dictionary
star

Tue Mar 31 2020 05:32:45 GMT+0000 (Coordinated Universal Time)

#python #python #dictionary #mergedictionary #dict

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension