Thread 1: Fatal error: expected attribute to be Codable

Not sure what I'm doing wrong here. I'm taking this opportunity to add persistence to an app that hadn't had it yet.

I followed the session advice but I get this crash when running it:

SwiftData/BackingData.swift:201: Fatal error: expected attribute to be Codable

The crash is on this line:

modelContext.insert(RentSplitDataModel())

The object being created and inserted there is simple and the compiler confirms it does conform to Codable: https://github.com/KyLeggiero/Rent-Split-for-iOS/blob/feature/MVP/Shared/Model/RentSplitDataModel.swift

Accepted Reply

This is caused by the fact that SwiftData does not yet support encoding custom Codable types, despite the claims from Apple. You'll have to make your model only use primitives such as Int, String, Date, etc

Add a Comment

Replies

please ignore this accidental reply

This is caused by the fact that SwiftData does not yet support encoding custom Codable types, despite the claims from Apple. You'll have to make your model only use primitives such as Int, String, Date, etc

Add a Comment

I had exactly the same error message during runtime. The solution for me was to change from .modelContainer(for: [StoredHabit.self], isAutoSaveEnabled: true, isUndoEnable: true) to .modelContainer(for: [StoredHabit.self]). After that, the error was gone and SwiftData worked properly again.

  • I was having this problem / crash when I modified ANY part of a model object - Ints, Strings, Dates, not just custom types. What's really bizarre is that this behavior was only happening on macOS apps, not iOS. The fix for me was also removing additional params (isAutoSaveEnabled: true, isUndoEnable: true) from the modelContainer modifier. Of course now I can't set the behavior I want, because the only way you can set isAutoSaveEnabled is through this constructor...

Add a Comment