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]Is it safe to reference previous VersionedSchema types in a newer schema's models array?
I'm building a SwiftData migration strategy and want to confirm whether it's officially supported to reference types from a previous VersionedSchema in a newer version's models array. Setup V1 defines all 28 models under its own namespace: static let versionIdentifier = Schema.Version(1, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, Self.UserModel.self, // ... 28 models ] } When migrating to V2, only ItemModel changes. To avoid copying unchanged model definitions into every new schema version, I include the previous version's types directly in V2's models array: static let versionIdentifier = Schema.Version(2, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, // V2 type (changed) ApplicationDatabaseSchema_V1_0_0.UserModel.self, // V1 type (unchanged) // ... other unchanged models referencing V1 types ] } extension ApplicationDatabaseSchema_V2_0_0 { @Model final class ItemModel { /* updated definition */ } } Questions Since SwiftData uses the simple class name (not the fully-qualified name including namespace) as the entity name, this appears to work in basic testing. But is mixing types from different schema version namespaces in a single models array officially supported, especially when models have relationships across versions? How does SwiftData handle inverse relationships when a newly defined V2 model references an unchanged V1 model? Is there a risk of schema corruption, runtime crashes during migration, or breaking changes in future SwiftData/iOS updates? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. What is the recommended pattern for handling unchanged models with relationships when migrating using VersionedSchema? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. Is there a recommended pattern for handling unchanged models when migrating with VersionedSchema?
1
0
53
4d
SwiftData predicate with optional chaining failing on OS 27
The following predicate (which returns results on OS 26) only returns results on OS 27 when I comment out the last line: reviewDescriptor = FetchDescriptor<Flashcard>( predicate: #Predicate { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && $0.dueDate < currentDate && !$0.isSuspended && advancedStudyEnabled.evaluate($0) && !($0.promotionLog?.isProcessing ?? false) // <- here }, sortBy: [SortDescriptor(\.previousInterval)] ) // where Flashcard — PromotionLog is a one-to-one optional relationship Because I’m still getting results on OS 26 from the same data, my guess is the line with optional chaining somehow causes the entire predicate to fail silently, without crashing the app. But I also don’t see any posts about it, so maybe it’s something I’m doing wrong? Is anyone else experiencing this? Any workarounds? ETA: However, this chaining appears to be working just fine: reviewDescriptor.predicate = #Predicate<Flashcard> { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && ($0.pronunciationLog?.dueDate ?? currentDate) < currentDate && $0.pronunciationLog?.practiceStateRaw != masteredRaw && !$0.isSuspended } So I’m a bit lost. Maybe the syntax of the first? Something about using it alongside .evaluate()? ETA2: After a bit more debugging, when && !($0.promotionLog?.isProcessing ?? false) is commented out, a Flashcard where promotionLog == nil shows up. But if promotionLog == nil, the line should evaluate to !(false), i.e. true. So why would that line stop the card from showing up in the first place?
1
0
126
5d
HistoryObserver eventCounter updating 9-16 times per app launch because of CloudKit syncing?
I created a finance tracking app. I wanted to use HistoryObserver to determine when Transactions are created/updated/deleted on another device with the same appleId, so I can update some charts I have an @Observable model that has this (simplified) setup: private(set) var transactionObserver: HistoryObserver? func setupHistoryObserver(modelContainer: ModelContainer) throws { transactionObserver = try HistoryObserver( observedModels: [Transaction.self], modelContainer: modelContainer, ) } var transactionUpdateTrigger: Int { transactionObserver?.eventCounter ?? 0 } I have the view setup with: .task(id: viewModel.transactionUpdateTrigger) { print("updating chart data: \(viewModel.transactionUpdateTrigger)") await updateChartData() } When I launch my app on my iPhone, I see: updating chart data: 0 updating chart data: 1 updating chart data: 2 updating chart data: 3 updating chart data: 4 updating chart data: 5 updating chart data: 6 updating chart data: 7 updating chart data: 8 updating chart data: 9 updating chart data: 10 On simulator, it only fires once: updating chart data: 0 The docs state: "When relevant changes are detected, the observer updates its eventCounter property." The happens every single time I try deploying my app to my iPhone on iOS 27 beta 8, but with varying numbers of eventCounter increments. I only have the app installed on a single device with my Apple Account. Why is this happening? There should be no changes to my models, as is clear because there's no issues when running this in simulator.
2
0
398
1w
Custom SwiftData DataStore
In the sample code below I am reading and writing ProductRecord model objects to PostgreSQL using a custom DataStore. However it is unclear to me how I can set this up such that I am able to also write other model object types to the same custom DataStore. Currently the ProductPostgresSnapshot is specific to the ProductRecord and the PostgresSwiftDataStore Snapshot refers to this ProductPostgresSnapshot. Any idea how I would change this to accommodate different model object types such as SupplierRecord ? Full console program shown below. Full console program
2
0
150
2w
#Predicate needs better validation
Hi, Overview I am finding #Predicate to be a bit tricky when used with Swift Data It compiles fine but crashes at runtime I know the fix for the problem just wondering if such pitfalls can be avoided at compile time Exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'can't use NULL on left hand side' terminating due to uncaught exception of type NSException CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x11209b000> , can't use NULL on left hand side with userInfo of (null) Questions Could anything be done to improve the safety to avoid such issues at runtime? Could I write the code better (better than the fix below) to avoid this? My thoughts Fix is possible however it wasn't obvious to me that there was a problem with my original code Would be nice to prevent them at compile time if possible. Currently got to be really careful to avoid such crashes. Code import Foundation import SwiftData @Model class Car { var name: String var modelRawValue: String? init(name: String, modelRawValue: String?) { self.name = name self.modelRawValue = modelRawValue } } enum CarModel: String, CaseIterable { case modelA case modelB } func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { let filterRawValues = filterModels?.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let filterRawValues { if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } else { true } } return predicate } func fetch(context: ModelContext) throws { let predicate = makePredicate(filterModels: nil) let fetchDescriptor = FetchDescriptor(predicate: predicate) do { let cars = try context.fetch(fetchDescriptor) print(cars.count) } catch { print("Error: \(error)") throw error } } Fix func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { // Checking nil condition even before creating the predicate fixes the issue guard let filterModels else { return .true } let filterRawValues = filterModels.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } return predicate }
3
0
581
2w
Migrating a Transformable attribute from CoreData to SwiftData
I am migrating a CloudKit-synchronized multi-platform app from CoreData to SwiftData. (Xcode 27.0 beta 5). One of my Models/Entities contains a Transformable attribute, which is defined in the CoreData model editor as: and which is defined in the generated CoreData class as @NSManaged nonisolated public var authorNames: [String]? Using the built-in translation took, Xcode created a Model wich included @Attribute(.transformable(by: "NSSecureUnarchiveFromDataTransformerName")) var authorNames: [String] = [] This compiles but does not run. In the function func getModelContainer() throws -> ModelContainer { let storeURL = try FileManager.default.url( for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(dbName) let modelConfiguration = ModelConfiguration( schema: dbSchema, url: storeURL, cloudKitDatabase: .automatic) let container = try ModelContainer( for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) return container } the app throws a fatal error in the ModelContainer initializer, SwiftData/SchemaCoreData.swift:398: Fatal error: Application must register a ValueTransformer for NSSecureUnarchiveFromDataTransformerName So I added the following line of code at the top of this function: ValueTransformer.setValueTransformer( NSSecureUnarchiveFromDataTransformer(), forName: .secureUnarchiveFromDataTransformerName) which also compiles but also throws the same fatal error in the same place. Can anyone suggest how to resolve this problem? This is a CloudKit synchronized app, so I am constrained in what I can do with this attribute.
1
0
179
3w
How do I write this #Predicate?
I have two Models which are defined (simplified) as follows: @Model final class Book { var id: UUID = UUID() var title: String = "" var authors: [Author]? = [] } @Model final class Author { var id: UUID = UUID() var name: String "" @Relationship(inverse: \Book.authors) var books: [Book]? = [] } Both Book.authors and Author.books are defined as optionals to satisfy the requirements of CloudKit, although it is clear from the above that neither is ever actually nil. I am trying to write a #Predicate that finds objects of type Book with a title that matches a specified title and with an author that matches a specified author. The function I'd like to write looks something like this: func find(title: String, author: Author, with context: ModelContext) -> Book? { let same = ComparisonResult.orderedSame let predicate = #Predicate<Book> { book in book.title.caseInsensitiveCompare(title) == same && book.authors!.contains(where: { $0.id == author.id }) } let descriptor = FetchDescriptor<Book>(predicate: predicate) return try? context.fetch(descriptor).first } This function fails to compile inside the expansion of the #Predicate macro with a very long error message: Cannot convert value of type (a long 'PredicateExpresions....') (aka (another log 'PredicateExpressions....')) to closure result type 'any StandardPredicateExpression<Bool>' I don't understand. How can I write this predicate so that it will both compile and work? I know how to work around this problem, but would like to both deepen my understanding of Swift and SwiftData and to avoid the (inelegant) workaround.
2
0
379
3w
Sandboxed macOS app using SwiftData and CloudKit cannot initialize CloudKit mirroring.
I have a Mac and iOS app intended to sync data in iCloud. Both apps in TestFlight, the iOS reads and writes to iCloud but the Mac fails as the App Sandbox denies mach-lookup com.apple.cloudd, so NSCloudKitMirroringDelegate` never reaches the daemon and setup fails permanently. I have a minimal app reproducing the issue on for the Mac app. I also submitted a feedback FB24450529
1
0
402
3w
CoreDate->SwiftData Migration & CloudKit
I have an existing CoreData + CloudKit app which I would like to migrate to SwiftData + CloudKit. In the existing CoreData implementation, I have many optional fields (most of which have default values). I want to migrated them to SwiftData non-optional fields with default values. Can someone please confirm that I can do this without causing issues for my existing (CoreData + CloudKit) customers? I.e., I know I can do the migration on the local copy of the database, but I am worried about the CloudKit interaction. Specifically, I'm concerned about properties such as var title: String? which is implemented in CloudKit as CD_title CD_title_ckAsset Can I safely implement this in SwiftData as var title: String = "" without causing a problem with the CloudKit implementation?
1
0
601
Aug ’26
PersistentModel Sendable?
Most documentation on the web indicates that SwiftData Model instances are not Sendable. However, the current Xcode (Version 27.0 beta 5 (27A5237l)) indicates that @Model is Sendable. Is this a new feature in 2027 or is it an error in the documentation? @attached(member, conformances: Observable, PersistentModel, Sendable, names: named($backingData), named(persistentBackingData), named(schemaMetadata), named(init), named($observationRegistrar), named(_SwiftDataNoType), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable, PersistentModel, Sendable) macro Model() I noticed this in the Quick Help as I was about to quit and go to bed. I'll check on this thread again after I wake up. If no answers I'll try writing a test case.
1
0
283
Aug ’26
Handling SwiftData Initialization Errors
The traditional way to initialize a SwiftData app looks like some variation of the following: @main struct TrainingCornerApp: App { let dbSchema: Schema = ... init() { } var body: some Scene { WindowGroup { MainAppScreen() .modelContainer(modelContainer) } } } private var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false, cloudKitDatabase: .automatic) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to create model container: \(error.localizedDescription)") } return container } } That is, if creating the modelContainer fails, the app aborts with a fatalError. What I want to do is have the application present an alert message for the user before terminating. (Let the user know the app can't run and suggest how to get help -- that sort of thing.) However, I've been having a hard time getting this to work, and it seems that the problems are related to trying to generate the alert at such an early stage in app startup. Does anyone have ideas/suggestions on how I might do this?
0
0
486
Aug ’26
SwiftData public sharing
I have an Apple app that uses SwiftData and icloud to sync the App's data across users' devices. Everything is working well. However, I am facing the following issue: SwiftData does not support public sharing of the object graph with other users via iCloud. How can I overcome this limitation without stopping using SwiftData? Thanks in advance!
3
7
1.3k
Aug ’26
Best practices
Hi everyone, I'm Alexsander. My friends call me Lexie. I have been working as software developer since 6 years ago, I have a lot of experience with Java and I started working with Angular since the last year. I am new in the Apple ecosystem and I have a question about best practices in full native Swift apps. There is any source (blogs, youtube channels, books, et al.) where I can understand the best practices? Like, I've heard about MVVM to scalable apps but I don't know exactly how to apply it. I think it's because usually I do not have my front-end components in the same project of my backend. I've been watching some videos from Apple Developer youtube channel and they are absolutely amazing, but they only keep teaching people to use the "raw" resources, not matching with the best practices. For example, I saw using swift data we do not need to write any SQL Query, unlike Java Ecossystem where even we use a ORM we usually write our queries natively, whether creating a table or fetching data.
2
0
1.1k
Aug ’26
SwiftData query returns "private" string in WidgetExtension
Hello, I am trying to set up Widgets in my app. I want to fetch my data in the SwiftData container that is shared between my app and my WidgetExtension with App Group. let modelContext = ModelContext(modelContainer) let predicate = #Predicate<Test>{ return $0.attribute == true } return try modelContext.fetch(FetchDescriptor (predicate: predicate, sortBy: [SortDescriptor(\Test.name)])) When this code is run in my WidgetExtension, returned objects attributes values are replaced with "" string. In the logs, Swift Data writes Query returned unrequested identifiers that have been dropped: <private> Any idea what I might be doing wrong to share my SwiftData between my App and my Widget? App Groups capability has been added to both apps and extension with the same identifier. Thank you
2
0
794
Jul ’26
SwiftData Decimal loses precision after save/fetch with a minimal reproduction
I believe I may have found a SwiftData persistence bug, but I'd like to verify that I'm not overlooking a documented limitation before filing Feedback. This minimal example appears to lose precision when persisting a Decimal: import Foundation import SwiftData @Model class Item { var value: Decimal init(_ value: Decimal) { self.value = value } } let original = Decimal(string: "123456789012345.6")! let container = try ModelContainer( for: Item.self, configurations: .init(isStoredInMemoryOnly: true) ) let context = ModelContext(container) context.insert(Item(original)) try context.save() let fetched = try ModelContext(container) .fetch(FetchDescriptor<Item>()) .first! print(original) print(fetched.value) Output: 123456789012345.6 123456789012346 A few observations from additional testing: Decimal(string:) preserves the value before persistence. Decimal ↔ NSDecimalNumber bridging preserves the value in separate tests. The value remains exact after model initialization, insertion, and save() on the registered object. The first Swift-visible precision loss appears after fetching from a new ModelContext. As a control, I repeated the test using Core Data with an NSInMemoryStoreType store and an NSDecimalAttributeType attribute. That round-tripped the tested values exactly. Inspecting the SQLite store generated by SwiftData showed the affected value stored as a REAL. At this point it appears the precision loss occurs somewhere in the SwiftData/Core Data persistence pipeline rather than in Decimal itself. Can anyone reproduce this, or is there a documented limitation on Decimal persistence in SwiftData that I have missed? If this is expected behavior, what is the recommended way to persist exact decimal values for financial applications?
0
0
647
Jul ’26
SwiftData Decimal loses precision after save/fetch with a minimal reproduction
I believe I may have found a SwiftData persistence bug, but I'd like to verify that I'm not overlooking a documented limitation before filing Feedback. This minimal example appears to lose precision when persisting a Decimal: import Foundation import SwiftData @Model class Item { var value: Decimal init(_ value: Decimal) { self.value = value } } let original = Decimal(string: "123456789012345.6")! let container = try ModelContainer( for: Item.self, configurations: .init(isStoredInMemoryOnly: true) ) let context = ModelContext(container) context.insert(Item(original)) try context.save() let fetched = try ModelContext(container) .fetch(FetchDescriptor<Item>()) .first! print(original) print(fetched.value) Output: 123456789012345.6 123456789012346 A few observations from additional testing: Decimal(string:) preserves the value before persistence. Decimal ↔ NSDecimalNumber bridging preserves the value in separate tests. The value remains exact after model initialization, insertion, and save() on the registered object. The first Swift-visible precision loss appears after fetching from a new ModelContext. As a control, I repeated the test using Core Data with an NSInMemoryStoreType store and an NSDecimalAttributeType attribute. That round-tripped the tested values exactly. Inspecting the SQLite store generated by SwiftData showed the affected value stored as a REAL. At this point it appears the precision loss occurs somewhere in the SwiftData/Core Data persistence pipeline rather than in Decimal itself. Can anyone reproduce this, or is there a documented limitation on Decimal persistence in SwiftData that I have missed? If this is expected behavior, what is the recommended way to persist exact decimal values for financial applications?
0
0
643
Jul ’26
SwiftData Model didset
Hi, I'm trying out new SwiftData in a small Xcode project. It seems that the property observers didSet and willSet don't work anymore for swift data anymore. In code like this, the didSet does nothing and seems to never be called. @Model public final class importConfig: Identifiable, ObservableObject{ @Attribute(.unique) public var id: UUID /// Name of the configuration var configName: String /// Numbers App document to open var numbersFilePath: URL? /// Indicate wether current <numbersFilePath> Numbers App document has been loaded and analyzed var isLoaded: Bool = false /// Current selected sheet var selectedSheetID: UUID? { didSet { selectedSheetID = nil print("test") } } } Am I doing something wrong or is it the expected behavior ? If it is the expected behavior, how can I add "business" rules when setting/unsetting value to model properties ? I tried to add rules directly with .onchange() in my views, but this way I have to repeat the same rules/code. Is there any alternative to do so ? Thank you
3
1
2.4k
Jul ’26
[SwiftData]Is it safe to reference previous VersionedSchema types in a newer schema's models array?
I'm building a SwiftData migration strategy and want to confirm whether it's officially supported to reference types from a previous VersionedSchema in a newer version's models array. Setup V1 defines all 28 models under its own namespace: static let versionIdentifier = Schema.Version(1, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, Self.UserModel.self, // ... 28 models ] } When migrating to V2, only ItemModel changes. To avoid copying unchanged model definitions into every new schema version, I include the previous version's types directly in V2's models array: static let versionIdentifier = Schema.Version(2, 0, 0) static let models: [any PersistentModel.Type] = [ Self.ItemModel.self, // V2 type (changed) ApplicationDatabaseSchema_V1_0_0.UserModel.self, // V1 type (unchanged) // ... other unchanged models referencing V1 types ] } extension ApplicationDatabaseSchema_V2_0_0 { @Model final class ItemModel { /* updated definition */ } } Questions Since SwiftData uses the simple class name (not the fully-qualified name including namespace) as the entity name, this appears to work in basic testing. But is mixing types from different schema version namespaces in a single models array officially supported, especially when models have relationships across versions? How does SwiftData handle inverse relationships when a newly defined V2 model references an unchanged V1 model? Is there a risk of schema corruption, runtime crashes during migration, or breaking changes in future SwiftData/iOS updates? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. What is the recommended pattern for handling unchanged models with relationships when migrating using VersionedSchema? The alternative — duplicating all 28 model class definitions in every schema version — introduces significant maintenance overhead. Is there a recommended pattern for handling unchanged models when migrating with VersionedSchema?
Replies
1
Boosts
0
Views
53
Activity
4d
SwiftData predicate with optional chaining failing on OS 27
The following predicate (which returns results on OS 26) only returns results on OS 27 when I comment out the last line: reviewDescriptor = FetchDescriptor<Flashcard>( predicate: #Predicate { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && $0.dueDate < currentDate && !$0.isSuspended && advancedStudyEnabled.evaluate($0) && !($0.promotionLog?.isProcessing ?? false) // <- here }, sortBy: [SortDescriptor(\.previousInterval)] ) // where Flashcard — PromotionLog is a one-to-one optional relationship Because I’m still getting results on OS 26 from the same data, my guess is the line with optional chaining somehow causes the entire predicate to fail silently, without crashing the app. But I also don’t see any posts about it, so maybe it’s something I’m doing wrong? Is anyone else experiencing this? Any workarounds? ETA: However, this chaining appears to be working just fine: reviewDescriptor.predicate = #Predicate<Flashcard> { $0.sourceLanguageRaw == rawLang && $0.cardStateRaw == reviewRaw && ($0.pronunciationLog?.dueDate ?? currentDate) < currentDate && $0.pronunciationLog?.practiceStateRaw != masteredRaw && !$0.isSuspended } So I’m a bit lost. Maybe the syntax of the first? Something about using it alongside .evaluate()? ETA2: After a bit more debugging, when && !($0.promotionLog?.isProcessing ?? false) is commented out, a Flashcard where promotionLog == nil shows up. But if promotionLog == nil, the line should evaluate to !(false), i.e. true. So why would that line stop the card from showing up in the first place?
Replies
1
Boosts
0
Views
126
Activity
5d
HistoryObserver eventCounter updating 9-16 times per app launch because of CloudKit syncing?
I created a finance tracking app. I wanted to use HistoryObserver to determine when Transactions are created/updated/deleted on another device with the same appleId, so I can update some charts I have an @Observable model that has this (simplified) setup: private(set) var transactionObserver: HistoryObserver? func setupHistoryObserver(modelContainer: ModelContainer) throws { transactionObserver = try HistoryObserver( observedModels: [Transaction.self], modelContainer: modelContainer, ) } var transactionUpdateTrigger: Int { transactionObserver?.eventCounter ?? 0 } I have the view setup with: .task(id: viewModel.transactionUpdateTrigger) { print("updating chart data: \(viewModel.transactionUpdateTrigger)") await updateChartData() } When I launch my app on my iPhone, I see: updating chart data: 0 updating chart data: 1 updating chart data: 2 updating chart data: 3 updating chart data: 4 updating chart data: 5 updating chart data: 6 updating chart data: 7 updating chart data: 8 updating chart data: 9 updating chart data: 10 On simulator, it only fires once: updating chart data: 0 The docs state: "When relevant changes are detected, the observer updates its eventCounter property." The happens every single time I try deploying my app to my iPhone on iOS 27 beta 8, but with varying numbers of eventCounter increments. I only have the app installed on a single device with my Apple Account. Why is this happening? There should be no changes to my models, as is clear because there's no issues when running this in simulator.
Replies
2
Boosts
0
Views
398
Activity
1w
Custom SwiftData DataStore
In the sample code below I am reading and writing ProductRecord model objects to PostgreSQL using a custom DataStore. However it is unclear to me how I can set this up such that I am able to also write other model object types to the same custom DataStore. Currently the ProductPostgresSnapshot is specific to the ProductRecord and the PostgresSwiftDataStore Snapshot refers to this ProductPostgresSnapshot. Any idea how I would change this to accommodate different model object types such as SupplierRecord ? Full console program shown below. Full console program
Replies
2
Boosts
0
Views
150
Activity
2w
#Predicate needs better validation
Hi, Overview I am finding #Predicate to be a bit tricky when used with Swift Data It compiles fine but crashes at runtime I know the fix for the problem just wondering if such pitfalls can be avoided at compile time Exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'can't use NULL on left hand side' terminating due to uncaught exception of type NSException CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x11209b000> , can't use NULL on left hand side with userInfo of (null) Questions Could anything be done to improve the safety to avoid such issues at runtime? Could I write the code better (better than the fix below) to avoid this? My thoughts Fix is possible however it wasn't obvious to me that there was a problem with my original code Would be nice to prevent them at compile time if possible. Currently got to be really careful to avoid such crashes. Code import Foundation import SwiftData @Model class Car { var name: String var modelRawValue: String? init(name: String, modelRawValue: String?) { self.name = name self.modelRawValue = modelRawValue } } enum CarModel: String, CaseIterable { case modelA case modelB } func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { let filterRawValues = filterModels?.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let filterRawValues { if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } else { true } } return predicate } func fetch(context: ModelContext) throws { let predicate = makePredicate(filterModels: nil) let fetchDescriptor = FetchDescriptor(predicate: predicate) do { let cars = try context.fetch(fetchDescriptor) print(cars.count) } catch { print("Error: \(error)") throw error } } Fix func makePredicate(filterModels: [CarModel]?) -> Predicate<Car> { // Checking nil condition even before creating the predicate fixes the issue guard let filterModels else { return .true } let filterRawValues = filterModels.map { $0.rawValue } let predicate = #Predicate<Car> { car in if let carModelRawValue = car.modelRawValue { filterRawValues.contains(carModelRawValue) } else { false } } return predicate }
Replies
3
Boosts
0
Views
581
Activity
2w
Migrating a Transformable attribute from CoreData to SwiftData
I am migrating a CloudKit-synchronized multi-platform app from CoreData to SwiftData. (Xcode 27.0 beta 5). One of my Models/Entities contains a Transformable attribute, which is defined in the CoreData model editor as: and which is defined in the generated CoreData class as @NSManaged nonisolated public var authorNames: [String]? Using the built-in translation took, Xcode created a Model wich included @Attribute(.transformable(by: "NSSecureUnarchiveFromDataTransformerName")) var authorNames: [String] = [] This compiles but does not run. In the function func getModelContainer() throws -> ModelContainer { let storeURL = try FileManager.default.url( for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(dbName) let modelConfiguration = ModelConfiguration( schema: dbSchema, url: storeURL, cloudKitDatabase: .automatic) let container = try ModelContainer( for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) return container } the app throws a fatal error in the ModelContainer initializer, SwiftData/SchemaCoreData.swift:398: Fatal error: Application must register a ValueTransformer for NSSecureUnarchiveFromDataTransformerName So I added the following line of code at the top of this function: ValueTransformer.setValueTransformer( NSSecureUnarchiveFromDataTransformer(), forName: .secureUnarchiveFromDataTransformerName) which also compiles but also throws the same fatal error in the same place. Can anyone suggest how to resolve this problem? This is a CloudKit synchronized app, so I am constrained in what I can do with this attribute.
Replies
1
Boosts
0
Views
179
Activity
3w
How do I write this #Predicate?
I have two Models which are defined (simplified) as follows: @Model final class Book { var id: UUID = UUID() var title: String = "" var authors: [Author]? = [] } @Model final class Author { var id: UUID = UUID() var name: String "" @Relationship(inverse: \Book.authors) var books: [Book]? = [] } Both Book.authors and Author.books are defined as optionals to satisfy the requirements of CloudKit, although it is clear from the above that neither is ever actually nil. I am trying to write a #Predicate that finds objects of type Book with a title that matches a specified title and with an author that matches a specified author. The function I'd like to write looks something like this: func find(title: String, author: Author, with context: ModelContext) -> Book? { let same = ComparisonResult.orderedSame let predicate = #Predicate<Book> { book in book.title.caseInsensitiveCompare(title) == same && book.authors!.contains(where: { $0.id == author.id }) } let descriptor = FetchDescriptor<Book>(predicate: predicate) return try? context.fetch(descriptor).first } This function fails to compile inside the expansion of the #Predicate macro with a very long error message: Cannot convert value of type (a long 'PredicateExpresions....') (aka (another log 'PredicateExpressions....')) to closure result type 'any StandardPredicateExpression<Bool>' I don't understand. How can I write this predicate so that it will both compile and work? I know how to work around this problem, but would like to both deepen my understanding of Swift and SwiftData and to avoid the (inelegant) workaround.
Replies
2
Boosts
0
Views
379
Activity
3w
Sandboxed macOS app using SwiftData and CloudKit cannot initialize CloudKit mirroring.
I have a Mac and iOS app intended to sync data in iCloud. Both apps in TestFlight, the iOS reads and writes to iCloud but the Mac fails as the App Sandbox denies mach-lookup com.apple.cloudd, so NSCloudKitMirroringDelegate` never reaches the daemon and setup fails permanently. I have a minimal app reproducing the issue on for the Mac app. I also submitted a feedback FB24450529
Replies
1
Boosts
0
Views
402
Activity
3w
CoreDate->SwiftData Migration & CloudKit
I have an existing CoreData + CloudKit app which I would like to migrate to SwiftData + CloudKit. In the existing CoreData implementation, I have many optional fields (most of which have default values). I want to migrated them to SwiftData non-optional fields with default values. Can someone please confirm that I can do this without causing issues for my existing (CoreData + CloudKit) customers? I.e., I know I can do the migration on the local copy of the database, but I am worried about the CloudKit interaction. Specifically, I'm concerned about properties such as var title: String? which is implemented in CloudKit as CD_title CD_title_ckAsset Can I safely implement this in SwiftData as var title: String = "" without causing a problem with the CloudKit implementation?
Replies
1
Boosts
0
Views
601
Activity
Aug ’26
PersistentModel Sendable?
Most documentation on the web indicates that SwiftData Model instances are not Sendable. However, the current Xcode (Version 27.0 beta 5 (27A5237l)) indicates that @Model is Sendable. Is this a new feature in 2027 or is it an error in the documentation? @attached(member, conformances: Observable, PersistentModel, Sendable, names: named($backingData), named(persistentBackingData), named(schemaMetadata), named(init), named($observationRegistrar), named(_SwiftDataNoType), named(access), named(withMutation)) @attached(memberAttribute) @attached(extension, conformances: Observable, PersistentModel, Sendable) macro Model() I noticed this in the Quick Help as I was about to quit and go to bed. I'll check on this thread again after I wake up. If no answers I'll try writing a test case.
Replies
1
Boosts
0
Views
283
Activity
Aug ’26
Handling SwiftData Initialization Errors
The traditional way to initialize a SwiftData app looks like some variation of the following: @main struct TrainingCornerApp: App { let dbSchema: Schema = ... init() { } var body: some Scene { WindowGroup { MainAppScreen() .modelContainer(modelContainer) } } } private var modelContainer: ModelContainer { let container: ModelContainer let modelConfiguration = ModelConfiguration(schema: dbSchema, isStoredInMemoryOnly: false, cloudKitDatabase: .automatic) do { container = try ModelContainer(for: dbSchema, migrationPlan: MigrationPlan.self, configurations: [modelConfiguration]) } catch { fatalError("Failed to create model container: \(error.localizedDescription)") } return container } } That is, if creating the modelContainer fails, the app aborts with a fatalError. What I want to do is have the application present an alert message for the user before terminating. (Let the user know the app can't run and suggest how to get help -- that sort of thing.) However, I've been having a hard time getting this to work, and it seems that the problems are related to trying to generate the alert at such an early stage in app startup. Does anyone have ideas/suggestions on how I might do this?
Replies
0
Boosts
0
Views
486
Activity
Aug ’26
SwiftData public sharing
I have an Apple app that uses SwiftData and icloud to sync the App's data across users' devices. Everything is working well. However, I am facing the following issue: SwiftData does not support public sharing of the object graph with other users via iCloud. How can I overcome this limitation without stopping using SwiftData? Thanks in advance!
Replies
3
Boosts
7
Views
1.3k
Activity
Aug ’26
Best practices
Hi everyone, I'm Alexsander. My friends call me Lexie. I have been working as software developer since 6 years ago, I have a lot of experience with Java and I started working with Angular since the last year. I am new in the Apple ecosystem and I have a question about best practices in full native Swift apps. There is any source (blogs, youtube channels, books, et al.) where I can understand the best practices? Like, I've heard about MVVM to scalable apps but I don't know exactly how to apply it. I think it's because usually I do not have my front-end components in the same project of my backend. I've been watching some videos from Apple Developer youtube channel and they are absolutely amazing, but they only keep teaching people to use the "raw" resources, not matching with the best practices. For example, I saw using swift data we do not need to write any SQL Query, unlike Java Ecossystem where even we use a ORM we usually write our queries natively, whether creating a table or fetching data.
Replies
2
Boosts
0
Views
1.1k
Activity
Aug ’26
How to respond to alarms that appear when I compile my app
When compiling the app on an iPhone running iOS 16, the following alerts appear. What steps should I take to resolve this? UIScene lifecycle will soon be required. Failure to adopt will result in an assert in the future. CoreUI: CUIThemeStore: No theme registered with id=0
Replies
0
Boosts
0
Views
617
Activity
Jul ’26
Loading an array
How can I pre-load an array that I created using Swiftdata? I am creating a deck of cards and I want the user to be able to add/delete from the deck.
Replies
1
Boosts
0
Views
502
Activity
Jul ’26
SwiftData query returns "private" string in WidgetExtension
Hello, I am trying to set up Widgets in my app. I want to fetch my data in the SwiftData container that is shared between my app and my WidgetExtension with App Group. let modelContext = ModelContext(modelContainer) let predicate = #Predicate<Test>{ return $0.attribute == true } return try modelContext.fetch(FetchDescriptor (predicate: predicate, sortBy: [SortDescriptor(\Test.name)])) When this code is run in my WidgetExtension, returned objects attributes values are replaced with "" string. In the logs, Swift Data writes Query returned unrequested identifiers that have been dropped: <private> Any idea what I might be doing wrong to share my SwiftData between my App and my Widget? App Groups capability has been added to both apps and extension with the same identifier. Thank you
Replies
2
Boosts
0
Views
794
Activity
Jul ’26
SwiftData Decimal loses precision after save/fetch with a minimal reproduction
I believe I may have found a SwiftData persistence bug, but I'd like to verify that I'm not overlooking a documented limitation before filing Feedback. This minimal example appears to lose precision when persisting a Decimal: import Foundation import SwiftData @Model class Item { var value: Decimal init(_ value: Decimal) { self.value = value } } let original = Decimal(string: "123456789012345.6")! let container = try ModelContainer( for: Item.self, configurations: .init(isStoredInMemoryOnly: true) ) let context = ModelContext(container) context.insert(Item(original)) try context.save() let fetched = try ModelContext(container) .fetch(FetchDescriptor<Item>()) .first! print(original) print(fetched.value) Output: 123456789012345.6 123456789012346 A few observations from additional testing: Decimal(string:) preserves the value before persistence. Decimal ↔ NSDecimalNumber bridging preserves the value in separate tests. The value remains exact after model initialization, insertion, and save() on the registered object. The first Swift-visible precision loss appears after fetching from a new ModelContext. As a control, I repeated the test using Core Data with an NSInMemoryStoreType store and an NSDecimalAttributeType attribute. That round-tripped the tested values exactly. Inspecting the SQLite store generated by SwiftData showed the affected value stored as a REAL. At this point it appears the precision loss occurs somewhere in the SwiftData/Core Data persistence pipeline rather than in Decimal itself. Can anyone reproduce this, or is there a documented limitation on Decimal persistence in SwiftData that I have missed? If this is expected behavior, what is the recommended way to persist exact decimal values for financial applications?
Replies
0
Boosts
0
Views
647
Activity
Jul ’26
SwiftData Decimal loses precision after save/fetch with a minimal reproduction
I believe I may have found a SwiftData persistence bug, but I'd like to verify that I'm not overlooking a documented limitation before filing Feedback. This minimal example appears to lose precision when persisting a Decimal: import Foundation import SwiftData @Model class Item { var value: Decimal init(_ value: Decimal) { self.value = value } } let original = Decimal(string: "123456789012345.6")! let container = try ModelContainer( for: Item.self, configurations: .init(isStoredInMemoryOnly: true) ) let context = ModelContext(container) context.insert(Item(original)) try context.save() let fetched = try ModelContext(container) .fetch(FetchDescriptor<Item>()) .first! print(original) print(fetched.value) Output: 123456789012345.6 123456789012346 A few observations from additional testing: Decimal(string:) preserves the value before persistence. Decimal ↔ NSDecimalNumber bridging preserves the value in separate tests. The value remains exact after model initialization, insertion, and save() on the registered object. The first Swift-visible precision loss appears after fetching from a new ModelContext. As a control, I repeated the test using Core Data with an NSInMemoryStoreType store and an NSDecimalAttributeType attribute. That round-tripped the tested values exactly. Inspecting the SQLite store generated by SwiftData showed the affected value stored as a REAL. At this point it appears the precision loss occurs somewhere in the SwiftData/Core Data persistence pipeline rather than in Decimal itself. Can anyone reproduce this, or is there a documented limitation on Decimal persistence in SwiftData that I have missed? If this is expected behavior, what is the recommended way to persist exact decimal values for financial applications?
Replies
0
Boosts
0
Views
643
Activity
Jul ’26
SwiftData Model didset
Hi, I'm trying out new SwiftData in a small Xcode project. It seems that the property observers didSet and willSet don't work anymore for swift data anymore. In code like this, the didSet does nothing and seems to never be called. @Model public final class importConfig: Identifiable, ObservableObject{ @Attribute(.unique) public var id: UUID /// Name of the configuration var configName: String /// Numbers App document to open var numbersFilePath: URL? /// Indicate wether current <numbersFilePath> Numbers App document has been loaded and analyzed var isLoaded: Bool = false /// Current selected sheet var selectedSheetID: UUID? { didSet { selectedSheetID = nil print("test") } } } Am I doing something wrong or is it the expected behavior ? If it is the expected behavior, how can I add "business" rules when setting/unsetting value to model properties ? I tried to add rules directly with .onchange() in my views, but this way I have to repeat the same rules/code. Is there any alternative to do so ? Thank you
Replies
3
Boosts
1
Views
2.4k
Activity
Jul ’26
Nedd help
Hy my name is max i would need help lurning i‘m trying to get developer mods to make apps
Replies
0
Boosts
0
Views
883
Activity
Jun ’26