Skip to content

Instantly share code, notes, and snippets.

@kyungpyoda
Created May 27, 2021 04:43
Show Gist options
  • Save kyungpyoda/620007ce0d858c1f95d5e3f3f98ac28b to your computer and use it in GitHub Desktop.
Save kyungpyoda/620007ce0d858c1f95d5e3f3f98ac28b to your computer and use it in GitHub Desktop.
[Swift] Encodable instance to dictionary
extension Encodable {
subscript(key: String) -> Any? {
return dictionary[key]
}
var dictionary: [String: Any] {
let dict: [String: Any]? = try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self)) as? [String: Any]
return dict ?? [:]
}
}
/*
struct Person: Codable {
var name: String
var age: Int
}
let person1 = Person(name: "Pio", age: 20)
let dict = person1.dictionary // ["name": "Pio", "age": 20]
let resultForName = person1["name"] // "Pio"
let resultForAge = person1["age"] // 20
let resultForInvalidKey = person1["pet"] // nil
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment