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

Answered by BenLeggiero_0 in 762497022

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

Start small .... not sure what MoneySplitter in your code is.

please ignore this accidental reply

@newwbee it's open-source. MoneySplitter is a simple struct with a lot of extension functions and Codable conformance: https://github.com/KyLeggiero/RentSplitTools/blob/765c748ff08e2fd0d4a1c00e8440f7ac3c6d703c/Sources/RentSplitTools/MoneySplitter.swift

Couldn't find a place where it says MoneySplitter conforms to Codable.

Accepted Answer

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

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.

Thread 1: Fatal error: expected attribute to be Codable
 
 
Q