Skip to content

Instantly share code, notes, and snippets.

@sidmani
Last active May 10, 2023 11:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sidmani/3860057e909a6e20277e8979e7b9a6c9 to your computer and use it in GitHub Desktop.
Save sidmani/3860057e909a6e20277e8979e7b9a6c9 to your computer and use it in GitHub Desktop.
quick protocol for creating dictionaries from types
// 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