ahti
(Lukas Stabe 🙃)
May 27, 2018, 12:03am
2
This is expected.
Only dictionaries with Int or String key types get encoded into keyed containers (-> JSON dictionaries). Since other encodable types could encode to dictionaries/arrays, which can't be used as keys, dictionaries will encode as an array of alternating keys and values when the key type is not Int or String.
This is the relevant code:
///
/// If the dictionary uses `String` or `Int` keys, the contents are encoded
/// in a keyed container. Otherwise, the contents are encoded as alternating
/// key-value pairs in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
@inlinable // FIXME(sil-serialize-all)
public func encode(to encoder: Encoder) throws {
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 container.encode(value, 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)
1 Like