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

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
52
4d
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
251
6d
#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 }
2
0
430
6d
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
169
6d
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
429
1w
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
169
2w
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
310
3w
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.1k
3w
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
843
3w
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
628
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
533
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
525
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.3k
Jul ’26
Best practice for centralizing SwiftData query logic and actions in an @Observable manager?
I'm building a SwiftUI app with SwiftData and want to centralize both query logic and related actions in a manager class. For example, let's say I have a reading app where I need to track the currently reading book across multiple views. What I want to achieve: @Observable class ReadingManager { let modelContext: ModelContext // Ideally, I'd love to do this: @Query(filter: #Predicate<Book> { $0.isCurrentlyReading }) var currentBooks: [Book] // ❌ But @Query doesn't work here var currentBook: Book? { currentBooks.first } func startReading(_ book: Book) { // Stop current book if any if let current = currentBook { current.isCurrentlyReading = false } book.isCurrentlyReading = true try? modelContext.save() } func stopReading() { currentBook?.isCurrentlyReading = false try? modelContext.save() } } // Then use it cleanly in any view: struct BookRow: View { @Environment(ReadingManager.self) var manager let book: Book var body: some View { Text(book.title) Button("Start Reading") { manager.startReading(book) } if manager.currentBook == book { Text("Currently Reading") } } } The problem is @Query only works in SwiftUI views. Without the manager, I'd need to duplicate the same query in every view just to call these common actions. Is there a recommended pattern for this? Or should I just accept query duplication across views as the intended SwiftUI/SwiftData approach?
4
0
1.7k
Jun ’26
Prevent SwiftData Upserts
Following the premise that database integrity should be handled by rules in the schema as much as possible, the automatic UPSERT whereby trying to create a record with the same unique key as a record that already exists does not trigger an INSERT error but automatically updates the existing record is pretty alien. I really don't want to enforce this on business logic and I want the backend to do the work. Is there away to prevent the UPSERT?
0
0
811
Jun ’26
Under what circumstances does @Query call body?
Hi I was wondering under what circumstances does @Query call body. Does it call it when the result set changes? E.g. object added/removed/moved. Does it also call when the result set is the same but a property of a model changed? I'd prefer 1, since models are @Observable my Views can handle tracking if they need to update when a property of a model changes. But I am concerned it is 2 which would cause unnecessary calls to body? E.g. a ForEach would needlessly be reinit since the model array is exactly the same. So which is it? By the way it would be useful if the docs could be updated with this important info. Thanks
1
0
863
Jun ’26
SwiftData, CloudKit and 2 AppleIDs
I have a SwiftData app that runs on iOS, iPadOS, and MacCatalyst and which uses CloudKit for inter-device sync. Unfortunately, I also have two AppleIDs (which I 'll refer to as OLDID and NEWID). Although all three devices (phone, pad and desktop) are currently set up with NEWID as the active AppleID, during development and testing, my desktop Mac used OLDID. Apparently, the system remembers the AppleID to use with each CloudKit app (based on the AppleID active at time of first use), because the desktop app and the mobile apps apparently sync to different AppleID accounts. I can delete the local database on the desktop and delete the local app on the mobile devices and in each case, reloading/rerunning the app causes the respective databases to be restored from the cloud. The two mobile devices sync with each other, but not with the desktop; the desktop doesn't sync with either device. And the two databases have decidedly different contents. My goal is to consolidate everything so that there is one database, shared and synced between desktop, pad, phone and cloud. I presume that there is a setting somewhere (but clearly NOT in the app's sandboxed container) that specifies what iCloud account to use for that (and each) app. Note: I have other apps which sync between all my devices, so the setting must be on a per-app basis. I also presume that if I changed it's value on my desktop (so that all three devices used the same AppleID for cloud services for my app), that the content of the local database on my desktop would be synced automatically to the NEWID cloud account and then (also automatically) synchronized with my mobile devices. I.e., I speculate that I can solve all my problems by changing that setting on my desktop Mac. So I have two questions: Is all this correct? How do I make this setting change. (I.e., where is it and how do I change it) Does anyone have any experience and can help with this issue? Thanks
3
0
1k
Jun ’26
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
52
Activity
4d
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
251
Activity
6d
#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
2
Boosts
0
Views
430
Activity
6d
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
169
Activity
6d
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
429
Activity
1w
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
169
Activity
2w
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
310
Activity
3w
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.1k
Activity
3w
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
843
Activity
3w
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
434
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
378
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
628
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
533
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
525
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.3k
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
770
Activity
Jun ’26
Best practice for centralizing SwiftData query logic and actions in an @Observable manager?
I'm building a SwiftUI app with SwiftData and want to centralize both query logic and related actions in a manager class. For example, let's say I have a reading app where I need to track the currently reading book across multiple views. What I want to achieve: @Observable class ReadingManager { let modelContext: ModelContext // Ideally, I'd love to do this: @Query(filter: #Predicate<Book> { $0.isCurrentlyReading }) var currentBooks: [Book] // ❌ But @Query doesn't work here var currentBook: Book? { currentBooks.first } func startReading(_ book: Book) { // Stop current book if any if let current = currentBook { current.isCurrentlyReading = false } book.isCurrentlyReading = true try? modelContext.save() } func stopReading() { currentBook?.isCurrentlyReading = false try? modelContext.save() } } // Then use it cleanly in any view: struct BookRow: View { @Environment(ReadingManager.self) var manager let book: Book var body: some View { Text(book.title) Button("Start Reading") { manager.startReading(book) } if manager.currentBook == book { Text("Currently Reading") } } } The problem is @Query only works in SwiftUI views. Without the manager, I'd need to duplicate the same query in every view just to call these common actions. Is there a recommended pattern for this? Or should I just accept query duplication across views as the intended SwiftUI/SwiftData approach?
Replies
4
Boosts
0
Views
1.7k
Activity
Jun ’26
Prevent SwiftData Upserts
Following the premise that database integrity should be handled by rules in the schema as much as possible, the automatic UPSERT whereby trying to create a record with the same unique key as a record that already exists does not trigger an INSERT error but automatically updates the existing record is pretty alien. I really don't want to enforce this on business logic and I want the backend to do the work. Is there away to prevent the UPSERT?
Replies
0
Boosts
0
Views
811
Activity
Jun ’26
Under what circumstances does @Query call body?
Hi I was wondering under what circumstances does @Query call body. Does it call it when the result set changes? E.g. object added/removed/moved. Does it also call when the result set is the same but a property of a model changed? I'd prefer 1, since models are @Observable my Views can handle tracking if they need to update when a property of a model changes. But I am concerned it is 2 which would cause unnecessary calls to body? E.g. a ForEach would needlessly be reinit since the model array is exactly the same. So which is it? By the way it would be useful if the docs could be updated with this important info. Thanks
Replies
1
Boosts
0
Views
863
Activity
Jun ’26
SwiftData, CloudKit and 2 AppleIDs
I have a SwiftData app that runs on iOS, iPadOS, and MacCatalyst and which uses CloudKit for inter-device sync. Unfortunately, I also have two AppleIDs (which I 'll refer to as OLDID and NEWID). Although all three devices (phone, pad and desktop) are currently set up with NEWID as the active AppleID, during development and testing, my desktop Mac used OLDID. Apparently, the system remembers the AppleID to use with each CloudKit app (based on the AppleID active at time of first use), because the desktop app and the mobile apps apparently sync to different AppleID accounts. I can delete the local database on the desktop and delete the local app on the mobile devices and in each case, reloading/rerunning the app causes the respective databases to be restored from the cloud. The two mobile devices sync with each other, but not with the desktop; the desktop doesn't sync with either device. And the two databases have decidedly different contents. My goal is to consolidate everything so that there is one database, shared and synced between desktop, pad, phone and cloud. I presume that there is a setting somewhere (but clearly NOT in the app's sandboxed container) that specifies what iCloud account to use for that (and each) app. Note: I have other apps which sync between all my devices, so the setting must be on a per-app basis. I also presume that if I changed it's value on my desktop (so that all three devices used the same AppleID for cloud services for my app), that the content of the local database on my desktop would be synced automatically to the NEWID cloud account and then (also automatically) synchronized with my mobile devices. I.e., I speculate that I can solve all my problems by changing that setting on my desktop Mac. So I have two questions: Is all this correct? How do I make this setting change. (I.e., where is it and how do I change it) Does anyone have any experience and can help with this issue? Thanks
Replies
3
Boosts
0
Views
1k
Activity
Jun ’26