Last active
May 10, 2023 11:32
quick protocol for creating dictionaries from types
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
// simple alternative to using swift 4's encodable protocol when you just need to quickly create a dictionary | |
// usage: | |
// struct SomeData: DictionaryEncodable { | |
// enum Key: String { | |
// case someValue | |
// } | |
// | |
// let someValue = 5 | |
// | |
// func encode(_ encoder: DictionaryEncoder) { | |
// encoder.encode(someValue, key: Key.someValue) | |
// } | |
// } | |
// let encoder = DictionaryEncoder() | |
// let dict = encoder.encode(someEncodableType) | |
class DictionaryEncoder { | |
var result: [String: Any] | |
init() { | |
result = [:] | |
} | |
func encode(_ encodable: DictionaryEncodable) -> [String: Any] { | |
encodable.encode(self) | |
return result | |
} | |
func encode<T, K>(_ value: T, key: K) where K: RawRepresentable, K.RawValue == String { | |
result[key.rawValue] = value | |
} | |
} | |
protocol DictionaryEncodable { | |
func encode(_ encoder: DictionaryEncoder) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment