Maximilian Berndt
Maximilian Berndt

Reputation: 21

SwiftData - Fatal error: Unexpected type for CompositeAttribute

I'm facing an issue when working with SwiftData (I feel certain I'm not alone) in the pet project I'm working on moving to SwiftData.

I re-created the issue(s) with the SwiftData example project below As you might think, I'm not super experienced with SwiftData but I couldn't really find any helpful documentation on this yet. As per official docs, anything conforming to Codable should be good for SwiftData.

FYI: In my pet project, the example basically maps to me storing players (Item) & each player containing a GameStatistics class (MyDictionaryWrapper) that stores a dictionary of [Game: Statistic] (here I'm using String: String for simplicity).


v1 -> This causes SwiftData - Fatal error: Unexpected type for CompositeAttribute: MyDictionaryWrapper

import SwiftData

@Model
final class Item {
    var timestamp: Date
    
    var testProperty: MyDictionaryWrapper = MyDictionaryWrapper()
    
    init(timestamp: Date) {
        self.timestamp = timestamp
    }
}

class MyDictionaryWrapper: Codable {
    var stats: [String: String] = [:]
    
    init(stats: [String : String] = [:]) {
        self.stats = stats
    }
}

v2 -> This causes Fatal error: failed to find a currently active container for MyDictionaryWrapper

import SwiftData

@Model
final class Item {
    var timestamp: Date
    
    var testProperty: MyDictionaryWrapper = MyDictionaryWrapper()
    
    init(timestamp: Date) {
        self.timestamp = timestamp
    }
}

@Model
class MyDictionaryWrapper {
    var stats: [String: String] = [:]
    
    init(stats: [String : String] = [:]) {
        self.stats = stats
    }
}

// ModelContainer setup (Xcode 15.3 SwiftData template)

import SwiftData

@main
struct SwiftDataTestApp: App {
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Customer.self,
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
    }
}

Which idea / direction is the right one? And what approach should I follow to fix it?

Should I reconsider the way I'm modelling my data to begin with?

Upvotes: 2

Views: 631

Answers (1)

Maximilian Berndt
Maximilian Berndt

Reputation: 21

V1, try struct instead of class and see if that helps

Thank you for the suggestion Joakim Danielson! I can't explain why it worked but it did.

Will have to learn a bit more about SwiftData while proceeding. Thanks to all who replied and had a look at my post :)

Upvotes: 0

Related Questions