Search code examples
swiftswiftdata

SwiftData: Fatal Error "Unexpected type for CompositeAttribute: Builtin.BridgeObject" when using nested enums in model


I'm getting a fatal error while trying to define a SwiftData model that includes nested enums. The error message I'm receiving is:

SwiftData/SchemaProperty.swift:373: Fatal error: Unexpected type for CompositeAttribute: Builtin.BridgeObject

Here's a simplified version of my code that can reproduce the issue:

import SwiftUI
import SwiftData

enum MyEnum: Identifiable, Codable {
    var id: String { UUID().uuidString }
    case aCase
}

enum MyOtherEnum: Identifiable, Codable {
    var id: String { UUID().uuidString }
    case aCase(Set<MyEnum>)
}

@Model
final class MyModel: Identifiable {

    init(id: String? = nil, something: MyOtherEnum? = nil) {
        self.id = id
        self.something = something
    }

    @Attribute(.unique)
    private(set) var id: String?

    private(set) var something: MyOtherEnum?
}


struct ContentView: View {
    var body: some View {
       Text("Content View")
    }
}

and:

import SwiftUI
import SwiftData

@main

    struct MyApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .modelContainer(for: [
                        MyModel.self
                    ])
            }
        }
    }

I guess that SwiftData might not handle nesting such as Set<MyEnum>?

EDIT:

I guess I could go with:

struct MyOtherEnum: Identifiable, Codable {
    let id: String
    let nestedEnum: Set<MyEnum>

    init(id: String? = nil, nestedEnum: Set<MyEnum>) {
        self.id = id ?? UUID().uuidString
        self.nestedEnum = nestedEnum
    }
}

but still, I am not sure why it works like this that I can't nest enums...


Solution

  • If you change from case aCase(Set<MyEnum>) to case aCase([MyEnum])

    your code works fine. Swift data only seems to have a problem with the Set.