Search results for

“SwiftData inheritance relationship”

4,986 results found

Post

Replies

Boosts

Views

Activity

SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: group, intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, d
0
0
731
Jun ’24
Access Relationship value from deleted model tombstone in SwiftData.
I’m developing an app using SwiftData. In my app, I have two models: User and Address. A user can have multiple addresses. I’m trying to use SwiftData History tracking to implement some logic when addresses are deleted. Specifically, I need to determine which user the address belonged to. From the documentation, I understand that you can preserve attributes from deleted models in a tombstone object using @Attribute(.preserveValueOnDeletion). However, this isn’t working when I try to apply this to a relationship value. Below is a simplified example of my attempts so far. I suspect that simply adding @Attribute(.preserveValueOnDeletion) to a relationship isn’t feasible. If that’s indeed the case, what would be the recommended approach to identify the user associated with an address after it has been deleted? Thank you. @Model class User { var name: String @Relationship(deleteRule: .cascade, inverse: Address.user) var addresses: [Address] = [] init(name: String) { sel
1
0
91
Mar ’26
How to handle required @relationship optionals in SwiftData CloudKit?
Hi all, As you know, when using SwiftData Cloudkit, all relationships are required to be optional. In my app, which is a list app, I have a model class Project that contains an array of Subproject model objects. A Subproject also contains an array of another type of model class and this chain goes on and on. In this type of pattern, it becomes really taxxing to handle the optionals the correct way, i.e. unwrap them as late as possible and display an error to the user if unable to. It seems like most developers don't even bother, they just wrap the array in a computed property that returns an empty array if nil. I'm just wondering what is the recommended way by Apple to handle these optionals. I'm not really familiar with how the CloudKit backend works, but if you have a simple list app that only saves to the users private iCloud, can I just handwave the optionals like so many do? Is it only big data apps that need to worry? Or should we always strive to handle them the correct way? If that's
3
0
199
Oct ’25
Reply to Swift Data issue with a recursive model class
Based on your description, SwiftData actually behaves correctly. To elaborate, let's look at your model: @Model final class Item { var name: String? var parent: Item? .... } You rely on SwiftData to infer that parent is a to-one relationship, which is fine, but as a part of the inference process, SwiftData also determines that the inverse relationship of parent is parent. So assuming you have two items, item1 and item2, when you set item1.parent to item2, SwiftData will automatically set item2.parent to item1, because it sees item2.parent as the inverse relationship of item1.parent. If you don't intent to have an inverse relationship, you can explicitly specify a nil inverse relationship using Relationship: @Model final class Item { var name: String? @Relationship(deleteRule: .nullify, inverse: nil) var parent: Item? .... } If your intent is to have a bi-directional to-one relationship, add an inverse relationship
Oct ’24
Reply to Bug? SwiftData + inheritance + optional many-to-one relationship
I encountered another bug with SwiftData and inheritance and reported it (FB21837287). This one is not related to CloudKit. Briefly, SwiftData crashes during auto-save when the schema contains: A base @Model class with at least one subclass (inheritance) A separate @Model class with a reference to the base class The crash occurs specifically when: There is a class inheritance hierarchy (Beta: Alpha) A separate class (Standalone) has a reference typed as the base class (Alpha?) Changing the reference from var ref: Alpha? to var ref: Beta? (subclass) eliminates the crash.
Feb ’26
Reply to SwiftData inverse relationship not updating
But are you saying that non-optional relationships do not work as intended in SwiftData? You can manage to use non-optional relationship by setting the relationship to a default value in the initializer, and then re-set it later after the real target object is inserted to the context. As I mentioned in the other post, I believe this is an area that SwiftData can be more intuitive, and would suggest that you file a feedback report for the SwiftData folks to take a look. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Sep ’24
SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
Hi there, I got two models here: Two Models, with Many-To-Many Relationship @Model final class PresetParams: Identifiable { @Attribute(.unique) var id: UUID = UUID() var positionX: Float = 0.0 var positionY: Float = 0.0 var positionZ: Float = 0.0 var volume: Float = 1.0 @Relationship(deleteRule: .nullify, inverse: Preset.presetAudioParams) var preset = [Preset]() init(position: SIMD3, volume: Float) { self.positionX = position.x self.positionY = position.y self.positionZ = position.z self.volume = volume self.preset = [] } var position: SIMD3 { get { return SIMD3(x: positionX, y: positionY, z: positionZ) } set { positionX = newValue.x positionY = newValue.y positionZ = newValue.z } } } @Model final class Preset: Identifiable { @Attribute(.unique) var id: UUID = UUID() var presetName: String var presetDesc: String? var presetAudioParams = [PresetParams]() // Many-To-Many Relationship. init(presetName: String, presetDesc: String? = nil) { self.presetName = presetName self.presetDesc =
1
0
160
Mar ’25
Querying data from one-to-many relationship by aggregate in swiftdata
Hi all, I've been struggling a bit with SwiftData, I have a really simple data model but I need to do a fairly complex query over a one-to-many relationship that results in aggregate values. And I want to be able to sort and filter those aggregates. The model looks like this: @Model class Category { var name: String var items = [Item]() } @Model class Item { var added: Date var checked: Date? } In a typical use case I'd expect their to be at most around 50 categories and perhaps 20 items per category. In my UI I would like to be able to sort categories in a couple of ways: by name, by date added and by date checked with a fallback on date added. Also, in my list view I want to be able to list categories and show the checked date of the most recently checked item. I can think of a couple of solutions here, to start of with I can do all the sorting and filtering client-side. In the list view I could retrieve all the categories and then find the most recently checked item per category and go fr
0
0
507
Jan ’24
Xcode 16.0. SwiftData Schema Fatal error: Inverse already set to another relationship
Hi, after upgrading to Xcode 16.0 I encountered the fact that when loading preview, I get an error: Fatal error: Inverse already set to another relationship - secondAccount - cannot assign to - firstAccount import Foundation import SwiftData import SwiftUI @Model class TransactionModel { @Relationship(inverse: AccountModel.accountTransactions) var firstAccount: AccountModel? /// <- here @Relationship(inverse: AccountModel.accountTransactions) var secondAccount: AccountModel? /// <- here @Relationship(inverse: DebtorModel.transactions) var debtor: DebtorModel? @Relationship(inverse: CategoryModel.transactions) var category: CategoryModel? init(account: AccountModel? = nil, secondAccount: AccountModel? = nil, debtor: DebtorModel? = nil, category: CategoryModel? = nil) { self.firstAccount = account self.secondAccount = secondAccount self.debtor = debtor self.category = category } } import SwiftData import SwiftUI @Model final public class Accou
1
0
709
Sep ’24
SwiftData does not retrieve my inverse one-to-many Relationship
Here is my models: import SwiftData @Model final public class FirstModel { let name: String @Relationship(deleteRule: .cascade, inverse: SecondModel.parent) var children = [SecondModel]() init(name: String) { self.name = name } } @Model final public class SecondModel { let parent: FirstModel let name: String @Relationship(deleteRule: .cascade, inverse: ThirdModel.parent) var children = [ThirdModel]() init(name: String, parent: FirstModel) { self.name = name self.parent = parent } } @Model final public class ThirdModel { let parent: SecondModel let name: String init(name: String, parent: SecondModel) { self.name = name self.parent = parent } } Then I create my model entries: let schema = Schema([ FirstModel.self, SecondModel.self, ThirdModel.self ]) let container = try ModelContainer(for: schema) let context = ModelContext(container) let firstModel = FirstModel(name: my first model) let secondModel = SecondModel(name: my second model, parent: firstModel) let thirdModel = ThirdModel(n
1
0
1.1k
May ’24
SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: group, intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, d
Replies
0
Boosts
0
Views
731
Activity
Jun ’24
Access Relationship value from deleted model tombstone in SwiftData.
I’m developing an app using SwiftData. In my app, I have two models: User and Address. A user can have multiple addresses. I’m trying to use SwiftData History tracking to implement some logic when addresses are deleted. Specifically, I need to determine which user the address belonged to. From the documentation, I understand that you can preserve attributes from deleted models in a tombstone object using @Attribute(.preserveValueOnDeletion). However, this isn’t working when I try to apply this to a relationship value. Below is a simplified example of my attempts so far. I suspect that simply adding @Attribute(.preserveValueOnDeletion) to a relationship isn’t feasible. If that’s indeed the case, what would be the recommended approach to identify the user associated with an address after it has been deleted? Thank you. @Model class User { var name: String @Relationship(deleteRule: .cascade, inverse: Address.user) var addresses: [Address] = [] init(name: String) { sel
Replies
1
Boosts
0
Views
91
Activity
Mar ’26
How to handle required @relationship optionals in SwiftData CloudKit?
Hi all, As you know, when using SwiftData Cloudkit, all relationships are required to be optional. In my app, which is a list app, I have a model class Project that contains an array of Subproject model objects. A Subproject also contains an array of another type of model class and this chain goes on and on. In this type of pattern, it becomes really taxxing to handle the optionals the correct way, i.e. unwrap them as late as possible and display an error to the user if unable to. It seems like most developers don't even bother, they just wrap the array in a computed property that returns an empty array if nil. I'm just wondering what is the recommended way by Apple to handle these optionals. I'm not really familiar with how the CloudKit backend works, but if you have a simple list app that only saves to the users private iCloud, can I just handwave the optionals like so many do? Is it only big data apps that need to worry? Or should we always strive to handle them the correct way? If that's
Replies
3
Boosts
0
Views
199
Activity
Oct ’25
Reply to Swift Data issue with a recursive model class
Based on your description, SwiftData actually behaves correctly. To elaborate, let's look at your model: @Model final class Item { var name: String? var parent: Item? .... } You rely on SwiftData to infer that parent is a to-one relationship, which is fine, but as a part of the inference process, SwiftData also determines that the inverse relationship of parent is parent. So assuming you have two items, item1 and item2, when you set item1.parent to item2, SwiftData will automatically set item2.parent to item1, because it sees item2.parent as the inverse relationship of item1.parent. If you don't intent to have an inverse relationship, you can explicitly specify a nil inverse relationship using Relationship: @Model final class Item { var name: String? @Relationship(deleteRule: .nullify, inverse: nil) var parent: Item? .... } If your intent is to have a bi-directional to-one relationship, add an inverse relationship
Replies
Boosts
Views
Activity
Oct ’24
Reply to Bug? SwiftData + inheritance + optional many-to-one relationship
I encountered another bug with SwiftData and inheritance and reported it (FB21837287). This one is not related to CloudKit. Briefly, SwiftData crashes during auto-save when the schema contains: A base @Model class with at least one subclass (inheritance) A separate @Model class with a reference to the base class The crash occurs specifically when: There is a class inheritance hierarchy (Beta: Alpha) A separate class (Standalone) has a reference typed as the base class (Alpha?) Changing the reference from var ref: Alpha? to var ref: Beta? (subclass) eliminates the crash.
Replies
Boosts
Views
Activity
Feb ’26
Reply to Solving the Circle-ellipse problem in Swift
One of the mentioned solutions is to drop the inheritance relationships and just use a common interface for common operations. Protocols do that, and aren't unique to Swift.
Topic: Programming Languages SubTopic: Swift Tags:
Replies
Boosts
Views
Activity
Jul ’15
Reply to SwiftData inverse relationship not updating
But are you saying that non-optional relationships do not work as intended in SwiftData? You can manage to use non-optional relationship by setting the relationship to a default value in the initializer, and then re-set it later after the real target object is inserted to the context. As I mentioned in the other post, I believe this is an area that SwiftData can be more intuitive, and would suggest that you file a feedback report for the SwiftData folks to take a look. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Replies
Boosts
Views
Activity
Sep ’24
SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
Hi there, I got two models here: Two Models, with Many-To-Many Relationship @Model final class PresetParams: Identifiable { @Attribute(.unique) var id: UUID = UUID() var positionX: Float = 0.0 var positionY: Float = 0.0 var positionZ: Float = 0.0 var volume: Float = 1.0 @Relationship(deleteRule: .nullify, inverse: Preset.presetAudioParams) var preset = [Preset]() init(position: SIMD3, volume: Float) { self.positionX = position.x self.positionY = position.y self.positionZ = position.z self.volume = volume self.preset = [] } var position: SIMD3 { get { return SIMD3(x: positionX, y: positionY, z: positionZ) } set { positionX = newValue.x positionY = newValue.y positionZ = newValue.z } } } @Model final class Preset: Identifiable { @Attribute(.unique) var id: UUID = UUID() var presetName: String var presetDesc: String? var presetAudioParams = [PresetParams]() // Many-To-Many Relationship. init(presetName: String, presetDesc: String? = nil) { self.presetName = presetName self.presetDesc =
Replies
1
Boosts
0
Views
160
Activity
Mar ’25
Reply to SwiftData Inheritance Query Specialized Model
FB19957253 (Crash on Hierarchical List children access from SwiftData inherited model) Again, thank you so much! I hope I gave enough informations, feel free to ask if I can do anything.
Replies
Boosts
Views
Activity
Aug ’25
Reply to Access Relationship value from deleted model tombstone in SwiftData.
Just to confirm that @Attribute(.preserveValueOnDeletion) doesn't preserve relationships. It only works for attributes. Given that, I don't see anything in the SwiftData history that can help restore a relationship between two SwiftData objects after they are deleted. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Mar ’26
Reply to Core Data - Error: Persistent History (3) has to be truncated due to the following entities being removed
Same issue here, after removing a SwiftData relationship.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Replies
Boosts
Views
Activity
Mar ’24
How does SKView inherit TraitCollection
I want to add a UIView to an SKView but wonder how that view will inherit traitcollection by default? And how can I manipulate it?
Replies
0
Boosts
0
Views
264
Activity
Oct ’20
Querying data from one-to-many relationship by aggregate in swiftdata
Hi all, I've been struggling a bit with SwiftData, I have a really simple data model but I need to do a fairly complex query over a one-to-many relationship that results in aggregate values. And I want to be able to sort and filter those aggregates. The model looks like this: @Model class Category { var name: String var items = [Item]() } @Model class Item { var added: Date var checked: Date? } In a typical use case I'd expect their to be at most around 50 categories and perhaps 20 items per category. In my UI I would like to be able to sort categories in a couple of ways: by name, by date added and by date checked with a fallback on date added. Also, in my list view I want to be able to list categories and show the checked date of the most recently checked item. I can think of a couple of solutions here, to start of with I can do all the sorting and filtering client-side. In the list view I could retrieve all the categories and then find the most recently checked item per category and go fr
Replies
0
Boosts
0
Views
507
Activity
Jan ’24
Xcode 16.0. SwiftData Schema Fatal error: Inverse already set to another relationship
Hi, after upgrading to Xcode 16.0 I encountered the fact that when loading preview, I get an error: Fatal error: Inverse already set to another relationship - secondAccount - cannot assign to - firstAccount import Foundation import SwiftData import SwiftUI @Model class TransactionModel { @Relationship(inverse: AccountModel.accountTransactions) var firstAccount: AccountModel? /// <- here @Relationship(inverse: AccountModel.accountTransactions) var secondAccount: AccountModel? /// <- here @Relationship(inverse: DebtorModel.transactions) var debtor: DebtorModel? @Relationship(inverse: CategoryModel.transactions) var category: CategoryModel? init(account: AccountModel? = nil, secondAccount: AccountModel? = nil, debtor: DebtorModel? = nil, category: CategoryModel? = nil) { self.firstAccount = account self.secondAccount = secondAccount self.debtor = debtor self.category = category } } import SwiftData import SwiftUI @Model final public class Accou
Replies
1
Boosts
0
Views
709
Activity
Sep ’24
SwiftData does not retrieve my inverse one-to-many Relationship
Here is my models: import SwiftData @Model final public class FirstModel { let name: String @Relationship(deleteRule: .cascade, inverse: SecondModel.parent) var children = [SecondModel]() init(name: String) { self.name = name } } @Model final public class SecondModel { let parent: FirstModel let name: String @Relationship(deleteRule: .cascade, inverse: ThirdModel.parent) var children = [ThirdModel]() init(name: String, parent: FirstModel) { self.name = name self.parent = parent } } @Model final public class ThirdModel { let parent: SecondModel let name: String init(name: String, parent: SecondModel) { self.name = name self.parent = parent } } Then I create my model entries: let schema = Schema([ FirstModel.self, SecondModel.self, ThirdModel.self ]) let container = try ModelContainer(for: schema) let context = ModelContext(container) let firstModel = FirstModel(name: my first model) let secondModel = SecondModel(name: my second model, parent: firstModel) let thirdModel = ThirdModel(n
Replies
1
Boosts
0
Views
1.1k
Activity
May ’24