Skip to content

Instantly share code, notes, and snippets.

@soapyigu
Created January 28, 2018 08:54
Show Gist options
  • Save soapyigu/3300ad17abdf4ccd27ee5534b132fb95 to your computer and use it in GitHub Desktop.
Save soapyigu/3300ad17abdf4ccd27ee5534b132fb95 to your computer and use it in GitHub Desktop.
extension Dictionary : Encodable /* where Key : Encodable, Value : Encodable */ {
public func encode(to encoder: Encoder) throws {
assertTypeIsEncodable(Key.self, in: type(of: self))
assertTypeIsEncodable(Value.self, in: type(of: self))
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(stringValue: key as! String)!
try (value as! Encodable).__encode(to: &container, forKey: codingKey)
}
} else if Key.self == Int.self {
// Since the keys are already Ints, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(intValue: key as! Int)!
try (value as! Encodable).__encode(to: &container, forKey: codingKey)
}
} else {
// Keys are Encodable but not Strings or Ints, so we cannot arbitrarily convert to keys.
// We can encode as an array of alternating key-value pairs, though.
var container = encoder.unkeyedContainer()
for (key, value) in self {
try (key as! Encodable).__encode(to: &container)
try (value as! Encodable).__encode(to: &container)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment