Created
January 28, 2018 08:54
-
-
Save soapyigu/3300ad17abdf4ccd27ee5534b132fb95 to your computer and use it in GitHub Desktop.
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 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