Search results for

“SwiftData inheritance relationship”

4,980 results found

Post

Replies

Boosts

Views

Activity

Bug? SwiftData + inheritance + optional many-to-one relationship
I've spent a few months writing an app that uses SwiftData with inheritance. Everything worked well until I tried adding CloudKit support. To do so, I had to make all relationships optional, which exposed what appears to be a bug. Note that this isn't a CloudKit issue -- it happens even when CloudKit is disabled -- but it's due to the requirement for optional relationships. In the code below, I get the following error on the second call to modelContext.save() when the button is clicked: Could not cast value of type 'SwiftData.PersistentIdentifier' (0x1ef510b68) to 'SimplePersistenceIdentifierTest.Computer' (0x1025884e0). I was surprised to find zero hit when Googling Could not cast value of type 'SwiftData.PersistentIdentifier'. Some things to note: Calling teacher.computers?.append(computer) instead of computer.teacher = teacher results in the same error. It only happens when Teacher inherits Person. It only happens if modelContext.save() is called both times. It
9
0
476
Jan ’26
SwiftData Class Inheritance
Hi, I'm considering using the new SwiftData class inheritance for a new app I'm building. I have a few questions: Is it working well enough for production? I have a number of different object types in my app. Some of them are very similar, and there's always a balance to be struck when it comes to splitting them into different types using class inheritance. Are there some good advice on when to use multiple classes instead of squeezing my object types into a single class? Is there advice against using class inheritance in multiple levels (3-4)? Claes
1
0
133
Jul ’25
SwiftData Relationships
I like knowing what I'm looking at in my code, so I'd like to know explicitly that the SwiftData variable that is the inverse is decorated with the @Relationship macro also, so: Can I use the @Relationship macro on the inverse class of a relationship if I don't specify it with .inverse ? IE: From Company @Relationship(deleteRule: .nullify, inverse: Address.company) var addresses: [Address]? and set the other as: From Address @Relationship var company: Company?
1
0
453
Jul ’24
SwiftData relationships
I am new to Swift, and I am trying to get a grip on SwiftData, which SO FAR seems pretty straightforward EXCEPT relationships between tables. I come from a MYSQL, SQLITE3 background and I am used to “Primary Keys”, Inner and Outer Joins, One-to-One and One-to-Many relationships. Which SwiftData does not appear to do (I think). I am following several reasonably good online tutorials on the subject, all of which gloss over how relationships work. The best one is a table for vegetables alongside a table of notes for each vegetable (A one-to-many relationship). The classes we set up for the schemas are as follows. import Foundation import SwiftData @Model class Vegetable { var name: String @Relationship(deleteRule: .cascade) var notes: [Note]? init(name: String) { self.name = name } } @Model class Note { var text: String var vegetable: Vegetable? init(text: String) { self.text = text } } I can’t comprehend how they work. None of the tutorials
1
0
1.2k
May ’24
Does SwiftData not allow model class inheritance?
Just for grins, I tried running the SwiftData generation tool on the existing Core Data model of a non-trivial app I've worked on for a decade or so. It's pretty substantial, and uses some more advanced features, so it seemed like an interesting test case. One of the warnings that was not reported by the UI, but which showed up in the generated code was quite a few instances of this: Entity inheritance on entity Bar (parent class Foo) is unsupported in SwiftData. Now that I'm looking at the code examples more carefully, I see an awful lot of final class, which maybe should have raised a red flag sooner. But to the best of my recollection, none of the sessions outright said that inheritance (was or) was not supported. Core Data has supported this functionality for a long time (maybe since the beginning). Assuming that this isn't supported in this first seed, are there plans to provide this functionality in the future? By the launch of iOS 17? (For the record, this model has
2
0
2.7k
Jun ’23
SwiftData Relationship
I have 2 classes and a relationship from one to another... I am getting an error while runtime. Can someone help me with this issue??.. @storageRestrictions(accesses: _$backingData, initializes: _trans) init(initialValue) { _$backingData.setValue(forKey: .trans, to: initialValue) _trans = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: .trans) return self.getValue(forKey: .trans) } set { _$observationRegistrar.withMutation(of: self, keyPath: .trans) { self.setValue(forKey: .trans, to: newValue) } } } Thread 1: EXC_BREAKPOINT (code=1, subcode=0x25256ead8) Below is my class... import SwiftData @Model final class Main { var name: String var limit: Double @Relationship(deleteRule: .cascade) var trans: [Child] = [] init(name: String, limit: Double, trans: [Child]) { self.name = name self.limit = limit self.trans = trans } } @Model final class Child { var trip: String var distance: Double init(trip: String, distance: Double) { self.trip = trip self.distance = dista
2
0
1.5k
Oct ’23
CloudKit backed SwiftData @Relationship
Hi, does anyone know how to get @Relationship in SwiftData to cascade to the CloudKit container? I've managed to get SwiftData classes to show up in CloudKit but they are not related in line with the @Relationship as per the example project: @Relationship(.cascade) var bucketListItem: [BucketListItem] = []` They are simply separate records. As result the cascade of deletes doesn't work. Any ideas?
2
0
1.2k
Jun ’23
SwiftData Unidirectional Relationships
Hi everyone I would like to achieve having unidirectional relationships in my SwiftData project (which I believe is possible: https://developer.apple.com/documentation/updates/swiftdata?changes=_9) but I'm afraid I'm struggling to overcome the errors I'm experiencing. For example, I have the following models: @Model final class Quota { @Attribute(.unique) var id: UUID var allowance: Int @Relationship(inverse: nil) var fish: Fish init(id: UUID = UUID(), fish: Fish, allowance: Int) { self.id = id self.fish = fish self.allowance = allowance } } @Model final class Fish { @Attribute(.unique) var id: Int var name: String init(id: Int, name: String) { self.id = id, self.name = name } } However, when I attempt to save a quota as so: let quota: Quota = .init(fish: Fish(id: 2, name: Salmon), allowance: 50) modelContext?.insert(quota) try save() I keep getting the following error: SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1570 %{PROPERTY}@ is
1
0
185
Mar ’26
Issue with SwiftData inheritance
Every time I insert a subclass (MYShapeLayer) into the model context, the app crashes with an error: DesignerPlayground crashed due to fatalError in BackingData.swift at line 908. Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb2dbc55f3f4c57f2 ))) with Optional(A6CA4F89-107F-4A66-BC49-DD7DAC689F77) struct ContentView: View { @Environment(.modelContext) private var modelContext @Query private var designs: [MYDesign] var layers: [MYLayer] { designs.first?.layers ?? [] } var body: some View { NavigationStack { List { ForEach(layers) { layer in Text(layer.description) } } .onAppear { let design = MYDesign(title: My Design) modelContext.insert(design) try? modelContext.save() } .toolbar { Menu(Add, systemImage: plus) { Button(action: addTextLayer) { Text(Add Text Layer) } Button(action: addShapeLayer) { Text(Add Shape Layer) } } } } } private func addTextLayer() { if let desig
1
0
163
Sep ’25
SwiftData Inheritance Query Specialized Model
Hi, I am currently experiencing some trouble when using parent model property in a predicate of a child model. I have an Item class that define parent-child relationship: @Model class Item { var timestamp: Date @Relationship(inverse: Item.children) var parent: Item? var children: [Item] init(parent: Item? = nil, children: [Item] = [], timestamp: Date = .now) { self.parent = parent self.children = children self.timestamp = timestamp } } I subclass this model like that: @available(iOS 26, *) @Model final class CollectionItem: Item { /* ... */ } When i make a Query in my View like that the system crashes: @Query( filter: #Predicate { $0.parent == nil }, sort: CollectionItem.name, ) private var collections: [CollectionItem] CrashReportError: Fatal Error in DataUtilities.swift AppName crashed due to fatalError in DataUtilities.swift at line 85. Couldn't find CollectionItem.)> on CollectionItem with fields [SwiftData.Schema.PropertyMetadata(name: name, keypath: CollectionItem., defaultValue: ni
9
0
368
Aug ’25
SwiftData data crashes with @Relationship
I've noticed that SwiftData's @Relationship seems to potentially cause application crashes. The crash error is shown in the image. Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist. @Model final class TrainInfo { @Relationship(deleteRule: .cascade, inverse: StopStation.trainInfo) var stations: [StopStation]? } @Model final class StopStation { @Relationship var trainInfo: TrainInfo? } /// some View var origin: StopStationDisplayable? { if let train = train as? TrainInfo { return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting }) } return nil } // Some other function or property func someFunction() { if let origin, let destination { // Function implementation } }
1
0
153
Apr ’25
SwiftData JSONDataStore with relationships
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, Create a custom data store with SwiftData, and (once updated for API changes since WWDC) that works fine. However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship? Here's my code; firstly the cleaned up code from the WWDC session: import SwiftData final class JSONStoreConfiguration: DataStoreConfiguration { typealias Store = JSONStore var name: String var schema: Schema? var fileURL: URL init(name: String, schema: Schema? = nil, fileURL: URL) { self.name = name self.schema = schema self.fileURL = fileURL } static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } final class JSONStore: DataStore { typealias Configuration
2
0
769
Nov ’24
Issues with SwiftData @Relationships in Swift Testing
Is it a known issue that when attempting to test SwiftData objects with relationships in Swift Testing there are errors that do not occur when the app is running? Example: @Relationship(deleteRule: .cascade, inverse: MBAccount.book) var accounts: [MBAccount] = [] and @Relationship var book: Microbook? Then the test: let book = Microbook(name: Julia's Cupcakes) let account1 = MBAccount(name: Chase Business Account) let account2 = MBAccount(name: Cash Drawer) account1.book = book account2.book = book #expect(account1.name == Chase Business Account) #expect(account2.type == asset) } Produces a fatal error while running test: SwiftData/PersistentModel.swift:321: Fatal error: Unable to find relationship on MBAccount for KeyPath MBAccount.book Any ideas?
1
0
835
Jun ’24
One to Many Relationship in SwiftData
Hi, I understand how to make one to many relationship in SwiftData and how to show the child records, like all cities of a country. But how to navigate and show the parent record from a child record, Like I want to show a country of a city ? like country.cities show all cities of a country, will cities.country work to show the country ? like cities.country.name ? Kind Regards
3
0
450
Sep ’24
Bug? SwiftData + inheritance + optional many-to-one relationship
I've spent a few months writing an app that uses SwiftData with inheritance. Everything worked well until I tried adding CloudKit support. To do so, I had to make all relationships optional, which exposed what appears to be a bug. Note that this isn't a CloudKit issue -- it happens even when CloudKit is disabled -- but it's due to the requirement for optional relationships. In the code below, I get the following error on the second call to modelContext.save() when the button is clicked: Could not cast value of type 'SwiftData.PersistentIdentifier' (0x1ef510b68) to 'SimplePersistenceIdentifierTest.Computer' (0x1025884e0). I was surprised to find zero hit when Googling Could not cast value of type 'SwiftData.PersistentIdentifier'. Some things to note: Calling teacher.computers?.append(computer) instead of computer.teacher = teacher results in the same error. It only happens when Teacher inherits Person. It only happens if modelContext.save() is called both times. It
Replies
9
Boosts
0
Views
476
Activity
Jan ’26
SwiftData Class Inheritance
Hi, I'm considering using the new SwiftData class inheritance for a new app I'm building. I have a few questions: Is it working well enough for production? I have a number of different object types in my app. Some of them are very similar, and there's always a balance to be struck when it comes to splitting them into different types using class inheritance. Are there some good advice on when to use multiple classes instead of squeezing my object types into a single class? Is there advice against using class inheritance in multiple levels (3-4)? Claes
Replies
1
Boosts
0
Views
133
Activity
Jul ’25
SwiftData Relationships
I like knowing what I'm looking at in my code, so I'd like to know explicitly that the SwiftData variable that is the inverse is decorated with the @Relationship macro also, so: Can I use the @Relationship macro on the inverse class of a relationship if I don't specify it with .inverse ? IE: From Company @Relationship(deleteRule: .nullify, inverse: Address.company) var addresses: [Address]? and set the other as: From Address @Relationship var company: Company?
Replies
1
Boosts
0
Views
453
Activity
Jul ’24
SwiftData relationships
I am new to Swift, and I am trying to get a grip on SwiftData, which SO FAR seems pretty straightforward EXCEPT relationships between tables. I come from a MYSQL, SQLITE3 background and I am used to “Primary Keys”, Inner and Outer Joins, One-to-One and One-to-Many relationships. Which SwiftData does not appear to do (I think). I am following several reasonably good online tutorials on the subject, all of which gloss over how relationships work. The best one is a table for vegetables alongside a table of notes for each vegetable (A one-to-many relationship). The classes we set up for the schemas are as follows. import Foundation import SwiftData @Model class Vegetable { var name: String @Relationship(deleteRule: .cascade) var notes: [Note]? init(name: String) { self.name = name } } @Model class Note { var text: String var vegetable: Vegetable? init(text: String) { self.text = text } } I can’t comprehend how they work. None of the tutorials
Replies
1
Boosts
0
Views
1.2k
Activity
May ’24
Does SwiftData not allow model class inheritance?
Just for grins, I tried running the SwiftData generation tool on the existing Core Data model of a non-trivial app I've worked on for a decade or so. It's pretty substantial, and uses some more advanced features, so it seemed like an interesting test case. One of the warnings that was not reported by the UI, but which showed up in the generated code was quite a few instances of this: Entity inheritance on entity Bar (parent class Foo) is unsupported in SwiftData. Now that I'm looking at the code examples more carefully, I see an awful lot of final class, which maybe should have raised a red flag sooner. But to the best of my recollection, none of the sessions outright said that inheritance (was or) was not supported. Core Data has supported this functionality for a long time (maybe since the beginning). Assuming that this isn't supported in this first seed, are there plans to provide this functionality in the future? By the launch of iOS 17? (For the record, this model has
Replies
2
Boosts
0
Views
2.7k
Activity
Jun ’23
SwiftData Relationship
I have 2 classes and a relationship from one to another... I am getting an error while runtime. Can someone help me with this issue??.. @storageRestrictions(accesses: _$backingData, initializes: _trans) init(initialValue) { _$backingData.setValue(forKey: .trans, to: initialValue) _trans = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: .trans) return self.getValue(forKey: .trans) } set { _$observationRegistrar.withMutation(of: self, keyPath: .trans) { self.setValue(forKey: .trans, to: newValue) } } } Thread 1: EXC_BREAKPOINT (code=1, subcode=0x25256ead8) Below is my class... import SwiftData @Model final class Main { var name: String var limit: Double @Relationship(deleteRule: .cascade) var trans: [Child] = [] init(name: String, limit: Double, trans: [Child]) { self.name = name self.limit = limit self.trans = trans } } @Model final class Child { var trip: String var distance: Double init(trip: String, distance: Double) { self.trip = trip self.distance = dista
Replies
2
Boosts
0
Views
1.5k
Activity
Oct ’23
SwiftData relationships — are they really areas?
In CoreData, many-relationships are implemented as NSSet objects. In the SwiftData examples, they are shown as arrays. Are they really arrays (i.e., order-preserving and duplicates allowed) or are they arrays made from CoreData NSSets? In my applications, this makes a HUGE difference.
Replies
1
Boosts
0
Views
1.6k
Activity
Jul ’23
CloudKit backed SwiftData @Relationship
Hi, does anyone know how to get @Relationship in SwiftData to cascade to the CloudKit container? I've managed to get SwiftData classes to show up in CloudKit but they are not related in line with the @Relationship as per the example project: @Relationship(.cascade) var bucketListItem: [BucketListItem] = []` They are simply separate records. As result the cascade of deletes doesn't work. Any ideas?
Replies
2
Boosts
0
Views
1.2k
Activity
Jun ’23
SwiftData Unidirectional Relationships
Hi everyone I would like to achieve having unidirectional relationships in my SwiftData project (which I believe is possible: https://developer.apple.com/documentation/updates/swiftdata?changes=_9) but I'm afraid I'm struggling to overcome the errors I'm experiencing. For example, I have the following models: @Model final class Quota { @Attribute(.unique) var id: UUID var allowance: Int @Relationship(inverse: nil) var fish: Fish init(id: UUID = UUID(), fish: Fish, allowance: Int) { self.id = id self.fish = fish self.allowance = allowance } } @Model final class Fish { @Attribute(.unique) var id: Int var name: String init(id: Int, name: String) { self.id = id, self.name = name } } However, when I attempt to save a quota as so: let quota: Quota = .init(fish: Fish(id: 2, name: Salmon), allowance: 50) modelContext?.insert(quota) try save() I keep getting the following error: SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=1570 %{PROPERTY}@ is
Replies
1
Boosts
0
Views
185
Activity
Mar ’26
Issue with SwiftData inheritance
Every time I insert a subclass (MYShapeLayer) into the model context, the app crashes with an error: DesignerPlayground crashed due to fatalError in BackingData.swift at line 908. Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb2dbc55f3f4c57f2 ))) with Optional(A6CA4F89-107F-4A66-BC49-DD7DAC689F77) struct ContentView: View { @Environment(.modelContext) private var modelContext @Query private var designs: [MYDesign] var layers: [MYLayer] { designs.first?.layers ?? [] } var body: some View { NavigationStack { List { ForEach(layers) { layer in Text(layer.description) } } .onAppear { let design = MYDesign(title: My Design) modelContext.insert(design) try? modelContext.save() } .toolbar { Menu(Add, systemImage: plus) { Button(action: addTextLayer) { Text(Add Text Layer) } Button(action: addShapeLayer) { Text(Add Shape Layer) } } } } } private func addTextLayer() { if let desig
Replies
1
Boosts
0
Views
163
Activity
Sep ’25
SwiftData Inheritance Query Specialized Model
Hi, I am currently experiencing some trouble when using parent model property in a predicate of a child model. I have an Item class that define parent-child relationship: @Model class Item { var timestamp: Date @Relationship(inverse: Item.children) var parent: Item? var children: [Item] init(parent: Item? = nil, children: [Item] = [], timestamp: Date = .now) { self.parent = parent self.children = children self.timestamp = timestamp } } I subclass this model like that: @available(iOS 26, *) @Model final class CollectionItem: Item { /* ... */ } When i make a Query in my View like that the system crashes: @Query( filter: #Predicate { $0.parent == nil }, sort: CollectionItem.name, ) private var collections: [CollectionItem] CrashReportError: Fatal Error in DataUtilities.swift AppName crashed due to fatalError in DataUtilities.swift at line 85. Couldn't find CollectionItem.)> on CollectionItem with fields [SwiftData.Schema.PropertyMetadata(name: name, keypath: CollectionItem., defaultValue: ni
Replies
9
Boosts
0
Views
368
Activity
Aug ’25
SwiftData data crashes with @Relationship
I've noticed that SwiftData's @Relationship seems to potentially cause application crashes. The crash error is shown in the image. Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist. @Model final class TrainInfo { @Relationship(deleteRule: .cascade, inverse: StopStation.trainInfo) var stations: [StopStation]? } @Model final class StopStation { @Relationship var trainInfo: TrainInfo? } /// some View var origin: StopStationDisplayable? { if let train = train as? TrainInfo { return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting }) } return nil } // Some other function or property func someFunction() { if let origin, let destination { // Function implementation } }
Replies
1
Boosts
0
Views
153
Activity
Apr ’25
SwiftData JSONDataStore with relationships
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, Create a custom data store with SwiftData, and (once updated for API changes since WWDC) that works fine. However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship? Here's my code; firstly the cleaned up code from the WWDC session: import SwiftData final class JSONStoreConfiguration: DataStoreConfiguration { typealias Store = JSONStore var name: String var schema: Schema? var fileURL: URL init(name: String, schema: Schema? = nil, fileURL: URL) { self.name = name self.schema = schema self.fileURL = fileURL } static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } final class JSONStore: DataStore { typealias Configuration
Replies
2
Boosts
0
Views
769
Activity
Nov ’24
Issues with SwiftData @Relationships in Swift Testing
Is it a known issue that when attempting to test SwiftData objects with relationships in Swift Testing there are errors that do not occur when the app is running? Example: @Relationship(deleteRule: .cascade, inverse: MBAccount.book) var accounts: [MBAccount] = [] and @Relationship var book: Microbook? Then the test: let book = Microbook(name: Julia's Cupcakes) let account1 = MBAccount(name: Chase Business Account) let account2 = MBAccount(name: Cash Drawer) account1.book = book account2.book = book #expect(account1.name == Chase Business Account) #expect(account2.type == asset) } Produces a fatal error while running test: SwiftData/PersistentModel.swift:321: Fatal error: Unable to find relationship on MBAccount for KeyPath MBAccount.book Any ideas?
Replies
1
Boosts
0
Views
835
Activity
Jun ’24
One to Many Relationship in SwiftData
Hi, I understand how to make one to many relationship in SwiftData and how to show the child records, like all cities of a country. But how to navigate and show the parent record from a child record, Like I want to show a country of a city ? like country.cities show all cities of a country, will cities.country work to show the country ? like cities.country.name ? Kind Regards
Replies
3
Boosts
0
Views
450
Activity
Sep ’24