Hello everybody
The following code builds and runs, and prints ["key": "value"]
, as expected:
typealias Dict = [String: String]
do {
let decoder = JSONDecoder()
let string = Data("""
{
"key": "value"
}
""".utf8)
let decoded = try decoder.decode(Dict.self, from: string)
print(decoded)
}
When I change the type of the key as follows:
struct String2: Decodable, Hashable {
let value: String
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(String.self)
}
}
typealias Dict = [String2: String]
do {
let decoder = JSONDecoder()
let string = Data("""
{
"key": "value"
}
""".utf8)
let decoded = try decoder.decode(Dict.self, from: string)
print(decoded)
}
I would expect it to behave similarly. The reality is that the code builds, but when running shows the following error:
Fatal error: Error raised at top level: Swift.DecodingError.typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil)): file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.8.25.8/swift/stdlib/public/core/ErrorType.swift, line 200
Such code does not even reach the content of the init(from decoder: Decoder) throws
function inside the String2
type.
Am I missing something? Any idea why this happens?
Thanks,
Andres