Hello everyone, I think I've discovered a bug in JSONDecoder and I'd like to get a quick sanity-check on this, as well as hopefully some ideas to work around the issue.
When attempting to decode a Decodable struct from JSON using JSONDecoder, the decoder throws an error when it encounters a dictionary that is keyed by an enum and somehow seems to think that the enum is an Array<Any>.
Here's a minimal reproducible example:
let jsonString = """
{
"variations": {
"plural": "tests",
"singular": "test"
}
}
"""
struct Json: Codable {
let variations: [VariationKind: String]
}
enum VariationKind: String, Codable, Hashable {
case plural = "plural"
case singular = "singular"
}
and then the actual decoding:
let json = try JSONDecoder().decode(
Json.self,
from: jsonString.data(using: .utf8)!
)
print(json)
The expected result would of course be the following:
Json(
variations: [
VariationKind.plural: "tests",
VariationKind.singular: "test"
]
)
But the actual result is an error:
Swift.DecodingError.typeMismatch(
Swift.Array<Any>,
Swift.DecodingError.Context(
codingPath: [
CodingKeys(stringValue: "variations", intValue: nil)
],
debugDescription: "Expected to decode Array<Any> but found a dictionary instead.",
underlyingError: nil
)
)
So basically, the JSONDecoder tries to decode Swift.Array<Any> but encounters a dictionary (duh), and I have no idea why this is happening. There are literally no arrays anywhere, neither in the actual JSON string, nor in any of the Codable structs.
Curiously, if I change the dictionary from [VariationKind: String] to [String: String], everything works perfectly.
So something about the enum seems to cause confusion in JSONDecoder. I've tried to fix this by implementing Decodable myself for VariationKind and using a singleValueContainer, but that causes exactly the same error.
Am I crazy, or is that a bug?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Since the iOS 18 and Xcode 16, I've been getting some really strange SwiftData errors when passing @Model classes around.
The error I'm seeing is the following:
SwiftData/BackingData.swift:409: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://34EE9059-A7B5-4484-96A0-D10786AC9FB0/TestApp/p2), implementation: SwiftData.PersistentIdentifierImplementation)
The same issue also happens when I try to retrieve a model from the ModelContext using its PersistentIdentifier and try to do anything with it. I have no idea what could be causing this.
I'm guessing this is just a bug in the iOS 18 Beta, since I couldn't find a single discussion about this on Google, I figured I'd mention it.
if someone has a workaround or something, that would be much appreciated.