In SwiftData, why can a Project's tasks array come back in a different order after relaunch, and how do you keep a user-defined order?
answer
- membership, not sequence
- fine until reloaded
- no ordered option on @Relationship
- a stored position to sort by
basics
~20 sSwiftData persists which tasks belong to a project, not the order of the array. Once the models are reloaded from the store, the elements can come back in any order, so store a position on the task and sort by it.
solid answer
~40 sSwiftData stores which models a to-many relationship links, not their order. While the same model instances stay in memory, `project.tasks` keeps the order you appended in, which is why the bug hides during a session. After a relaunch, or in a fresh context that reads from the store, the array can come back in a different order. `@Relationship` has no ordering option: `Schema.Relationship.Option` declares only `.unique`. To keep a user's order, add a stored property such as `var position: Int` to the task, sort with `tasks.sorted { $0.position < $1.position }` or fetch tasks sorted by it, and rewrite the positions when the user reorders rows. Never read meaning, such as "oldest first", from the raw array order.
code
swift · 27 linesimport SwiftData
@Model
final class Project {
var name: String
@Relationship(deleteRule: .cascade, inverse: \ProjectTask.project)
var tasks: [ProjectTask] = []
// The array's order is not persisted; sort by a stored field.
var orderedTasks: [ProjectTask] {
tasks.sorted { $0.position < $1.position }
}
init(name: String) { self.name = name }
}
@Model
final class ProjectTask {
var title: String
var position: Int
var project: Project?
init(title: String, position: Int) {
self.title = title
self.position = position
}
}go deeper
Remember that a relationship array's order is not saved; sort by a stored field before showing it.
Explain why the order holds in memory but not after a reload, and how a position field plus a sorted view fixes it.
Write the test that actually catches it, by reopening the store, and handle ties and reorders without rewriting the whole list.
Make sort keys part of model review: any list a user can reorder ships with a stored order field from its first schema version.
## The symptom A project-management app shows a project's tasks with `ForEach(project.tasks)`. During development the list looks right: tasks appear in the order they were added. After a relaunch the same list shows them shuffled. Nobody changed the code, and the data is all there, but the order is gone. ## Why it happens A **to-many relationship** in SwiftData records *which* models are linked, not the sequence they were linked in. The Swift array type is how the relationship is exposed to your code; it is not a promise that the store remembers positions. - **In memory**, while the same `Project` instance and its tasks stay alive in a context, the array keeps the order of your appends. That is why the bug survives a whole session. - **After a reload**, when a new container or context reads the project back from the store, the array is rebuilt from the stored links, and its order is not the one you appended in. In a test that appended 40 tasks in order and reopened the store, they came back shuffled. - **There is no switch for it.** `@Relationship` takes options of type `Schema.Relationship.Option`, and the only one the SDK declares is `.unique`. Unlike Core Data, whose relationships can be marked ordered, SwiftData has no ordered to-many relationship. So any meaning attached to array order is lost on reload: "first task", "last added", or a user's drag-to-reorder. ## Keeping an order that survives The fix is to make order **data**: 1. Add a stored property to the related model, for example `var position: Int`. 2. Assign it when the task is created, typically one past the current maximum in that project. 3. Read through a sorted view: a computed `orderedTasks` that sorts `tasks` by `position`, or a fetch of the project's tasks sorted by `\.position`. 4. When the user moves rows, rewrite `position` on the tasks that moved, then save. | Approach | Survives relaunch | Cost | |---|---|---| | Rely on the array's order | no | none, until it breaks | | Sort by `createdAt` | yes | only gives creation order | | Sort by a stored `position` | yes | rewrite positions on reorder | A creation date is enough when the order you need *is* creation order. A user-controlled order needs its own field. Either way, the sort key is an ordinary stored attribute, so it is saved, migrated and synced like any other. ## Details worth getting right - **Ties.** Two tasks with the same `position` sort unpredictably; add a tiebreaker such as the title or a creation date. - **Reordering cost.** Moving one row with integer positions can rewrite many tasks. That is fine for the tens or hundreds of tasks in a project; for very long lists, spacing positions apart (or using a `Double` and inserting between neighbours) touches fewer rows. - **New tasks.** Assign `position` in the same function that appends the task to its project, so no code path can create a task without one. - **Many-to-many.** The same holds for both arrays of a many-to-many relationship: sort tags by `name` or another stored field before showing them. - **Tests.** An in-memory test that appends and reads back in the same context will pass even with the bug. Reopen the store or use a second context, then assert the sorted order. ## Where order bugs hide - `ForEach(project.tasks)` in a view, showing the raw relationship. - `project.tasks.first` or `.last` used to mean "oldest" or "newest". - An export or share sheet that writes tasks in array order. - Code that appends a task and then assumes `tasks.last` is the new one after the app has relaunched. Each of these reads correctly in a short manual test and fails only after the store has been reopened, which is why the fix belongs in the model (a stored key and a sorted accessor) rather than in each screen. ## What to say in an interview The short version: the store keeps relationship membership, not array order; the array order is only stable while the objects stay loaded; and a user-defined order needs a stored sort key that the app maintains. Mentioning that `@Relationship` offers no ordered option, and that a same-context test cannot catch the bug, shows you have hit it in practice.
- Why does a unit test that appends tasks and reads them back usually pass anyway?Because it reads the same model instances it just modified, and in memory the array keeps the append order. The order is lost only when the project is rebuilt from the store. Reopen the container, or fetch in a second context, before asserting the order.
- How do you persist a drag-to-reorder in a SwiftUI list of SwiftData tasks?Let the list's move action compute the new order of the visible, position-sorted tasks, then assign each moved task its new `position` and save. The display always reads the sorted view, so the next launch shows the same order the user chose.
- A SwiftData to-many array keeps its append order across launches.
- Calling save() after each append makes SwiftData store the array's order.
- @Relationship has an ordered option like Core Data's ordered relationships.
- If the order is right in a same-context test, it is right after relaunch.
- project.tasks.first is the oldest task in the project.