Created
May 27, 2021 04:43
-
-
Save kyungpyoda/620007ce0d858c1f95d5e3f3f98ac28b to your computer and use it in GitHub Desktop.
[Swift] Encodable instance to dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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