SwiftData

RSS for tag

Learn to write model code declaratively to add managed persistence and efficient model fetching.

SwiftData Documentation

Posts under SwiftData subtopic

Post

Replies

Boosts

Views

Activity

SwiftData #Predicate in Swift 6 language mode
I'm trying to migrate over to the Swift 6 language mode, but the biggest issue I'm facing is that any use of SwiftData #Predicate or SortDescriptor results in this warning from the compiler: Type 'ReferenceWritableKeyPath<GuruSchemaV2.Rubric, Bool>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode Here is an example predicate, from a static method on the Rubric type: static func notArchived() -> Predicate<Rubric> { return #Predicate<Rubric> { rubric in !rubric.archived } } And the error highlights line 5 of the expanded macro: Foundation.Predicate<Rubric>({ rubric in PredicateExpressions.build_Negation( PredicateExpressions.build_KeyPath( root: PredicateExpressions.build_Arg(rubric), keyPath: \.archived ) ) }) What is the correct way to reference properties of a model type using #Predicate?
0
1
112
Jun ’25
SwiftData Models not working after updating to macOS 26
Im working on an app which have a lot of diffrent models which are having relationships one to many and so on and on macos Sequoia and Sonoma everything is working but on Tahoe i have this error SwiftData/SchemaProperty.swift:286: Fatal error: Illegal attempt to create a property that's a sequence of a non-codable type (_buffer - _ArrayBuffer). Did you mean to use a transformable attribute? I also use computed properties to perform login on model value change like property name is var name: String{ get:{ self._name} set:{ self._name = $0 } } var _name: String = "" I no where use ArrayBuffer i just use [Double] it its needed
3
1
125
Jun ’25
SwiftData Transient Macro Observability
I have a SwiftData model that includes a transient image, declared as follows: @Transient var image: UIImage? It appears that SwiftData does not track changes to transient properties and so the following view will not update when the image changes from nil to an actual image. ZStack(alignment: .topTrailing) { if let image = item?.image { Image(uiImage: image) } else { ProgressView() } } Ideally, the SwiftData model would still observe changes in transient properties and just not persist them. As such, other code that works with observable objects would work as otherwise expected.
0
0
75
Jun ’25
Is SwiftData missing some APIs?
I was taking a look through SwiftData documentation for any changes coming from WWDC 2025 regarding my previous issues that was left unaddressed… KeyPaths are still not provided in Schema.Attribute as it was with Schema.Relationship. I also don’t see an initializer for HistoryTombstone, making it impossible to set up HistoryDelete protocol from what I can gather. I would appreciate a confirmation that we have been provided everything we need to complete the custom store, because I don’t know if everything I need has been provided or if some APIs have not been opened up. Thank you.
0
0
53
Jun ’25
SwiftData Predicate for optional to-many (as required by CloudKit) relationships crashes
Fails with "to-many key not allowed here" // parent.children?.contains(where: { // $0.name == "Abbiejean" // }) != nil parent.children.flatMap { children in children.contains(where: { $0.name == "Abbijean" }) } == true How are we supposed to query on relationships? This is a huge problem. This is a major limitation blocking migration of CoreData to SwiftData. We can do this with NSPredicate: let moodAnalysis = NSPredicate(format: "ANY moodAnalysis.labels.title == %@", label.description) let stateOfMinds = NSPredicate(format: "SUBQUERY(stateOfMinds, $x, SUBQUERY($x.labels, $y, $y.title == %@).@count > 0).@count > 0", label.description) The accepted answer on stack overflow is: you can't Document says that optionals are allowed in predicates The SwiftData team has made a big show of saying that we can use idiomatic swift for our predicates. But we cannot even filter on relationships when the container is backed by CloudKit... That should be a HUGE warning in the documentation. "For those of you who are considering a costly refactor from CoreData to SwiftData, and are currently using CloudKit, all relationships are mandatory optional arrays, and you can't write predicates on them"
3
0
96
Jun ’25
How to use SwiftData with MVVM architecture?
Hello all! I'm still fairly new to SwiftData, but have recently integrated it into one of my apps which has been going great. Currently, I have this integrated into my project like so (code simplified for illustration): @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Todo.self) } } struct ContentView: View { @Query(sort: \Todo.date) var todos: [Todo] @Environment(\.modelContext) var moc var body: some View { ... } } In my app, the ContentView struct then also contains business logic in the form of various methods to create and modify entities stored in SwiftData. In order to achieve better separation of concerns and make SwiftTesting the view easier, I'd love to move all this business logic code out into a view model. Unfortunately, I understand that this causes issues due to view models not having access to the SwiftUI environment, making it difficult to inject the model container into a view model and using that model to initialize queries. There are some approaches to this that I found which end up defining another layer on top of SwiftData, but I can see how doing that may result in state syncronization issues between what is stored in SwiftData and the model accessing it. Given that MVVM is so popular and widely used, is there a recommended approach of doing this in a consistent way while still preserving state safety between the SwiftData model and the view model? Thanks for any suggestions! Cheers, Robin
1
0
149
Jun ’25
Add App Group to Existing SwiftData App
I have an existing app that uses SwiftData and now want to add widgets. I added the widget extension, created an App Group to use for the main app target and widget targets and successfully created the widget. However, when testing the updates I often experience data loss - as though the including the widget extension is creating a new instance of modelContainer. Am I missing something to ensure there won't be any data loss when adding the App Group and widget extension? For additional context: I’ve followed the Backyard Birds example code except that it uses a separate app package. My app does not use an external app package, but I am using some elements of the DataGeneration file. My files containing the SwiftData models have Target Memberships for both the main app target and widget extension target. In the TimelineProvider for my widgets, I'm doing the following: let modelContext = ModelContext(DataGeneration.container) init() { DataGeneration.generateAllData(modelContext: modelContext) } My DataGeneration file (simplified) is as follows. When adding the widget target, I sometimes see the log for "Creating instance of DataGeneration". import Foundation import SwiftData @Model class DataGeneration { var requiresInitialization: Bool = true init(requiresInitialization: Bool = true) { self.requiresInitialization = requiresInitialization } private func generateInitialData(modelContext: ModelContext) { if requiresInitialization { let budget = Budget() modelContext.insert(budget) requiresInitialization = false } } private static func instance(with modelContext: ModelContext) -> DataGeneration { if let result = try! modelContext.fetch(FetchDescriptor<DataGeneration>()).first { logger.info("Found instance of DataGeneration") return result } else { logger.info("Creating instance of DataGeneration") let instance = DataGeneration() modelContext.insert(instance) return instance } } static func generateAllData(modelContext: ModelContext) { let instance = instance(with: modelContext) instance.generateInitialData(modelContext: modelContext) } } extension DataGeneration { static let container = try! ModelContainer(for: schema, configurations: [.init(isStoredInMemoryOnly: DataGenerationOptions.inMemoryPersistence)]) static let schema = SwiftData.Schema([ DataGeneration.self, Budget.self ]) }
4
0
254
Jun ’25
SwiftData superclass prevents usage of ID
New subclassing is a great addition to SwiftData, while trying to utilize the superclass type for selection state I’m seeing the following error: @available(macOS 26.0, *) @Model public class Asset { … } var assetSelection: [Asset.ID] = [] Error: 'ID' is inaccessible due to '@_spi' protection level Replacing the type with a subclassed swift data model of Asset works, but to handle mixed selection and the new .dragContainer modifier I need to be able to use the superclass. Is this intended behavior?
7
0
143
Jun ’25
How to handle completely adopting SwiftData when you need all the lightweight migrations defined in the xcdatamodeld?
At the end over every "how to adopt SwiftData in a CoreData app" it says, now go ahead and delete the xcdatamodeld files. But my xcdatamodeld contains all the migrations necessary to even support SwiftData in the first place. If I have 10 versions of my CoreData model, and the 10th matches the first version of my SwiftData model... But a user is on the 7th version, and then upgrade to the new app that doesn't contain any xcdatamodeld files.. How are you actually supposed to handle this? I don't want to keep supporting both. I just want to use SwiftData.
0
0
75
Jun ’25
SwiftData App Crashes only in TestFlight...
I have been building a SwiftUI/SwiftData app for some time that has been working fine in both the simulator and devices I have loaded from Xcode. These include two iPhones an iPad and a VisionPro. I have gotten to the point where I wanted to do some external beta testing so uploaded the App to the AppStore and then had a couple of users download via TestFlight. Unfortunately the App crashes and I have been unable to figure out why based on the feedback that I have gotten. The app has 4 Models that are linked in a fairly straightforward manner. There is a Habit class that is the central object. An Aspiration class that may have several Habits associated with it. An Anchor Class and a Celebration Class both attach to a Habit. I was able to get my neighbor to use TestFlight to download the App and it crashed when trying to insert a Habit but Aspirations, Anchors and Celebrations work fine and can be added, stored and deleted without issue. I then had my neighbor connect their phone to my computer and I download the app directly and it works fine as expected even when not connected to the debugger so clearly something is different between the two environments and I am at a loss so could use someone with good knowledge to help me figure this out.
4
0
92
Jul ’25
Crash when adding large JSON data to SwiftData: Could not cast value of type '__NSCFBoolean' to 'NSString'
Within the app main struct, the SwiftData modelContainer is created by fetching and decoding JSON from remote site. The decoded data is inserted into the modelContext. Immediately thereafter, the app crashes with the error Could not cast value of type '__NSCFBoolean' to 'NSString' . I have run the JSON from the site through JSON lint and it is correctly structured. The JSON data is structured as follows: Overview object which includes a Result object which includes a List Array. Each List object includes a Books Array. I have run the app through AI and the result indicates that there is data corruption when adding the data to the database. The AI rewrote the code such that the book data is encoded into a data blob and then adds the data to the database, instead of adding the individual books (which is extensive.) This approach works without crashing, but I would like to find out if this is indeed a SwiftData issue.
4
0
77
Jul ’25
SwiftData #Predicate in Swift 6 language mode
I'm trying to migrate over to the Swift 6 language mode, but the biggest issue I'm facing is that any use of SwiftData #Predicate or SortDescriptor results in this warning from the compiler: Type 'ReferenceWritableKeyPath<GuruSchemaV2.Rubric, Bool>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode Here is an example predicate, from a static method on the Rubric type: static func notArchived() -> Predicate<Rubric> { return #Predicate<Rubric> { rubric in !rubric.archived } } And the error highlights line 5 of the expanded macro: Foundation.Predicate<Rubric>({ rubric in PredicateExpressions.build_Negation( PredicateExpressions.build_KeyPath( root: PredicateExpressions.build_Arg(rubric), keyPath: \.archived ) ) }) What is the correct way to reference properties of a model type using #Predicate?
Replies
0
Boosts
1
Views
112
Activity
Jun ’25
SwiftData Models not working after updating to macOS 26
Im working on an app which have a lot of diffrent models which are having relationships one to many and so on and on macos Sequoia and Sonoma everything is working but on Tahoe i have this error SwiftData/SchemaProperty.swift:286: Fatal error: Illegal attempt to create a property that's a sequence of a non-codable type (_buffer - _ArrayBuffer). Did you mean to use a transformable attribute? I also use computed properties to perform login on model value change like property name is var name: String{ get:{ self._name} set:{ self._name = $0 } } var _name: String = "" I no where use ArrayBuffer i just use [Double] it its needed
Replies
3
Boosts
1
Views
125
Activity
Jun ’25
SwiftData Transient Macro Observability
I have a SwiftData model that includes a transient image, declared as follows: @Transient var image: UIImage? It appears that SwiftData does not track changes to transient properties and so the following view will not update when the image changes from nil to an actual image. ZStack(alignment: .topTrailing) { if let image = item?.image { Image(uiImage: image) } else { ProgressView() } } Ideally, the SwiftData model would still observe changes in transient properties and just not persist them. As such, other code that works with observable objects would work as otherwise expected.
Replies
0
Boosts
0
Views
75
Activity
Jun ’25
Is SwiftData missing some APIs?
I was taking a look through SwiftData documentation for any changes coming from WWDC 2025 regarding my previous issues that was left unaddressed… KeyPaths are still not provided in Schema.Attribute as it was with Schema.Relationship. I also don’t see an initializer for HistoryTombstone, making it impossible to set up HistoryDelete protocol from what I can gather. I would appreciate a confirmation that we have been provided everything we need to complete the custom store, because I don’t know if everything I need has been provided or if some APIs have not been opened up. Thank you.
Replies
0
Boosts
0
Views
53
Activity
Jun ’25
SwiftData Predicate for optional to-many (as required by CloudKit) relationships crashes
Fails with "to-many key not allowed here" // parent.children?.contains(where: { // $0.name == "Abbiejean" // }) != nil parent.children.flatMap { children in children.contains(where: { $0.name == "Abbijean" }) } == true How are we supposed to query on relationships? This is a huge problem. This is a major limitation blocking migration of CoreData to SwiftData. We can do this with NSPredicate: let moodAnalysis = NSPredicate(format: "ANY moodAnalysis.labels.title == %@", label.description) let stateOfMinds = NSPredicate(format: "SUBQUERY(stateOfMinds, $x, SUBQUERY($x.labels, $y, $y.title == %@).@count > 0).@count > 0", label.description) The accepted answer on stack overflow is: you can't Document says that optionals are allowed in predicates The SwiftData team has made a big show of saying that we can use idiomatic swift for our predicates. But we cannot even filter on relationships when the container is backed by CloudKit... That should be a HUGE warning in the documentation. "For those of you who are considering a costly refactor from CoreData to SwiftData, and are currently using CloudKit, all relationships are mandatory optional arrays, and you can't write predicates on them"
Replies
3
Boosts
0
Views
96
Activity
Jun ’25
How to use SwiftData with MVVM architecture?
Hello all! I'm still fairly new to SwiftData, but have recently integrated it into one of my apps which has been going great. Currently, I have this integrated into my project like so (code simplified for illustration): @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } .modelContainer(for: Todo.self) } } struct ContentView: View { @Query(sort: \Todo.date) var todos: [Todo] @Environment(\.modelContext) var moc var body: some View { ... } } In my app, the ContentView struct then also contains business logic in the form of various methods to create and modify entities stored in SwiftData. In order to achieve better separation of concerns and make SwiftTesting the view easier, I'd love to move all this business logic code out into a view model. Unfortunately, I understand that this causes issues due to view models not having access to the SwiftUI environment, making it difficult to inject the model container into a view model and using that model to initialize queries. There are some approaches to this that I found which end up defining another layer on top of SwiftData, but I can see how doing that may result in state syncronization issues between what is stored in SwiftData and the model accessing it. Given that MVVM is so popular and widely used, is there a recommended approach of doing this in a consistent way while still preserving state safety between the SwiftData model and the view model? Thanks for any suggestions! Cheers, Robin
Replies
1
Boosts
0
Views
149
Activity
Jun ’25
Add App Group to Existing SwiftData App
I have an existing app that uses SwiftData and now want to add widgets. I added the widget extension, created an App Group to use for the main app target and widget targets and successfully created the widget. However, when testing the updates I often experience data loss - as though the including the widget extension is creating a new instance of modelContainer. Am I missing something to ensure there won't be any data loss when adding the App Group and widget extension? For additional context: I’ve followed the Backyard Birds example code except that it uses a separate app package. My app does not use an external app package, but I am using some elements of the DataGeneration file. My files containing the SwiftData models have Target Memberships for both the main app target and widget extension target. In the TimelineProvider for my widgets, I'm doing the following: let modelContext = ModelContext(DataGeneration.container) init() { DataGeneration.generateAllData(modelContext: modelContext) } My DataGeneration file (simplified) is as follows. When adding the widget target, I sometimes see the log for "Creating instance of DataGeneration". import Foundation import SwiftData @Model class DataGeneration { var requiresInitialization: Bool = true init(requiresInitialization: Bool = true) { self.requiresInitialization = requiresInitialization } private func generateInitialData(modelContext: ModelContext) { if requiresInitialization { let budget = Budget() modelContext.insert(budget) requiresInitialization = false } } private static func instance(with modelContext: ModelContext) -> DataGeneration { if let result = try! modelContext.fetch(FetchDescriptor<DataGeneration>()).first { logger.info("Found instance of DataGeneration") return result } else { logger.info("Creating instance of DataGeneration") let instance = DataGeneration() modelContext.insert(instance) return instance } } static func generateAllData(modelContext: ModelContext) { let instance = instance(with: modelContext) instance.generateInitialData(modelContext: modelContext) } } extension DataGeneration { static let container = try! ModelContainer(for: schema, configurations: [.init(isStoredInMemoryOnly: DataGenerationOptions.inMemoryPersistence)]) static let schema = SwiftData.Schema([ DataGeneration.self, Budget.self ]) }
Replies
4
Boosts
0
Views
254
Activity
Jun ’25
SwiftData superclass prevents usage of ID
New subclassing is a great addition to SwiftData, while trying to utilize the superclass type for selection state I’m seeing the following error: @available(macOS 26.0, *) @Model public class Asset { … } var assetSelection: [Asset.ID] = [] Error: 'ID' is inaccessible due to '@_spi' protection level Replacing the type with a subclassed swift data model of Asset works, but to handle mixed selection and the new .dragContainer modifier I need to be able to use the superclass. Is this intended behavior?
Replies
7
Boosts
0
Views
143
Activity
Jun ’25
How to handle completely adopting SwiftData when you need all the lightweight migrations defined in the xcdatamodeld?
At the end over every "how to adopt SwiftData in a CoreData app" it says, now go ahead and delete the xcdatamodeld files. But my xcdatamodeld contains all the migrations necessary to even support SwiftData in the first place. If I have 10 versions of my CoreData model, and the 10th matches the first version of my SwiftData model... But a user is on the 7th version, and then upgrade to the new app that doesn't contain any xcdatamodeld files.. How are you actually supposed to handle this? I don't want to keep supporting both. I just want to use SwiftData.
Replies
0
Boosts
0
Views
75
Activity
Jun ’25
SwiftData App Crashes only in TestFlight...
I have been building a SwiftUI/SwiftData app for some time that has been working fine in both the simulator and devices I have loaded from Xcode. These include two iPhones an iPad and a VisionPro. I have gotten to the point where I wanted to do some external beta testing so uploaded the App to the AppStore and then had a couple of users download via TestFlight. Unfortunately the App crashes and I have been unable to figure out why based on the feedback that I have gotten. The app has 4 Models that are linked in a fairly straightforward manner. There is a Habit class that is the central object. An Aspiration class that may have several Habits associated with it. An Anchor Class and a Celebration Class both attach to a Habit. I was able to get my neighbor to use TestFlight to download the App and it crashed when trying to insert a Habit but Aspirations, Anchors and Celebrations work fine and can be added, stored and deleted without issue. I then had my neighbor connect their phone to my computer and I download the app directly and it works fine as expected even when not connected to the debugger so clearly something is different between the two environments and I am at a loss so could use someone with good knowledge to help me figure this out.
Replies
4
Boosts
0
Views
92
Activity
Jul ’25
Crash when adding large JSON data to SwiftData: Could not cast value of type '__NSCFBoolean' to 'NSString'
Within the app main struct, the SwiftData modelContainer is created by fetching and decoding JSON from remote site. The decoded data is inserted into the modelContext. Immediately thereafter, the app crashes with the error Could not cast value of type '__NSCFBoolean' to 'NSString' . I have run the JSON from the site through JSON lint and it is correctly structured. The JSON data is structured as follows: Overview object which includes a Result object which includes a List Array. Each List object includes a Books Array. I have run the app through AI and the result indicates that there is data corruption when adding the data to the database. The AI rewrote the code such that the book data is encoded into a data blob and then adds the data to the database, instead of adding the individual books (which is extensive.) This approach works without crashing, but I would like to find out if this is indeed a SwiftData issue.
Replies
4
Boosts
0
Views
77
Activity
Jul ’25