Reorder Filtered SwiftUI Lists Without Moving Hidden Rows
A reading list has five items. Turn on Favorites only, drag the last favorite to the top, and turn the filter off again. Where should the two hidden items end up?
That is a model decision, even when SwiftUI supplies the drag animation. The filter has hidden some rows. It has not granted permission to rearrange their furniture.
We’ll use the iOS 27 reordering APIs with one explicit policy: reorder the visible items within the slots they already occupy in the full collection. Hidden items keep their positions. We’ll also reject outdated moves before changing anything.
Choose what a filtered move means
Imagine the full order is A, B, C, D, E, with A, C and E marked as favorites. Moving E before A produces:
| Collection | Before | After |
|---|---|---|
| Favorites shown | A, C, E | E, A, C |
| Full list | A, B, C, D, E | E, B, A, D, C |
B and D remain at the same indices. The operation fills the three favorite slots with their new order.
Another valid product policy would remove E from the master array and insert it directly before A. That produces E, A, B, C, D and shifts the hidden rows. Choose deliberately; neither result follows automatically from the word “reorder.”
This example assumes the underlying array represents manual order, and the filter preserves that order. If results are sorted by title, date or a server’s relevance score, dragging them won’t change the sorting rule. Disable reordering there, or give the user an explicit manual-order mode.
Let SwiftUI describe the move by identity
The filtered-list question on Stack Overflow illustrates a familiar trap: the visible array and stored array differ, so applying the same offsets to both cannot be trusted. The discussion has an answer; it doesn’t establish a hidden-row policy for us.
In the current API, ReorderDifference supplies source IDs and a destination: before another ID, or at the end. Apple’s WWDC26 code-along demonstrates the interaction, and Natalia Panferova’s walkthrough explains wiring the modifiers into a collection. Here we’ll extend that foundation with filtered model updates and failure handling.
The view below requires iOS 27 or later. The complete sample was checked with Xcode 27.2 and Swift 6.4.2. The nonisolated model declarations use Swift 6.2-or-later syntax and keep this synchronous value logic independent of a project’s default MainActor setting. They don’t make shared mutable storage safe to access concurrently.
Download the runnable example and checks, or put the next two blocks into an iOS app and show ReadingList() inside a NavigationStack. The demo keeps its order in memory; persistence is your app’s separate responsibility.
Reorder current values, then put them back
The helper takes the expected visible IDs, the moved IDs and an optional destination ID. nil means the end of the visible collection.
It recomputes the current projection before accepting the move. If its IDs or order differ, the caller must refresh and try again. Changes confined to hidden items are allowed; the operation uses their current positions. It also rejects duplicate identities, unknown sources and hidden or missing destinations. All validation happens before the first write.
import Foundation
// nil means the end of the visible collection.
@discardableResult
nonisolated func moveVisibleItems<Item: Identifiable>(
in items: inout [Item],
matching isVisible: (Item) -> Bool,
expectedIDs: [Item.ID],
sources: [Item.ID],
before destination: Item.ID?
) -> Bool {
let slots = items.indices.filter { isVisible(items[$0]) }
let visible = slots.map { items[$0] }
let movingIDs = Set(sources)
guard Set(items.map(\.id)).count == items.count,
visible.map(\.id) == expectedIDs,
!sources.isEmpty,
movingIDs.count == sources.count,
movingIDs.isSubset(of: Set(expectedIDs)) else {
return false
}
if let destination {
guard expectedIDs.contains(destination) else { return false }
// Dropping a group onto one of its own items changes nothing.
if movingIDs.contains(destination) { return true }
}
let moving = visible.filter { movingIDs.contains($0.id) }
var reordered = visible.filter { !movingIDs.contains($0.id) }
let insertionIndex: Int
if let destination {
guard let index = reordered.firstIndex(where: {
$0.id == destination
}) else { return false }
insertionIndex = index
} else {
insertionIndex = reordered.endIndex
}
reordered.insert(contentsOf: moving, at: insertionIndex)
for (index, item) in zip(slots, reordered) {
items[index] = item
}
return true
}
nonisolated struct ReadingItem: Identifiable, Equatable {
let id: String
var title: String
var isFavorite: Bool
static let examples: [ReadingItem] = [
.init(id: "a", title: "Async sequences", isFavorite: true),
.init(id: "b", title: "Build settings", isFavorite: false),
.init(id: "c", title: "Caching", isFavorite: true),
.init(id: "d", title: "Debugging", isFavorite: false),
.init(id: "e", title: "Error handling", isFavorite: true)
]
}
Notice three details:
slotsbelongs to the full array. Only those positions are overwritten; hidden items are never removed and reinserted.- The moved block follows its current visible order, even if
sourcesarrives in another order. A destination inside that block is treated as a successful no-op. - We move current records, not copies captured when the view rendered. A title updated since then survives, provided the visible IDs and their order still match.
The helper is linear in the collection size, assuming ordinary constant-time ID hashing. It allocates temporary arrays to keep validation separate from mutation. This is an in-memory ordering operation, not a database transaction or a conflict-resolution protocol.
Connect the same operation to dragging and menus
Apple’s reordering guide pairs reorderable() on the ForEach with reorderContainer on its enclosing container. There is no built-in array mutation hidden inside the callback.
Capture the filter and visible IDs used for that rendering. The callback checks them against the current model before applying its result. A row menu offers Move up and Move down through the same helper, so dragging isn’t the only way to change the order.
import SwiftUI
@available(iOS 27.0, macOS 27.0, *)
struct ReadingList: View {
@State private var items = ReadingItem.examples
@State private var favoritesOnly = true
@State private var moveRejected = false
var body: some View {
let filter = favoritesOnly
let visible = items.filter { !filter || $0.isFavorite }
let ids = visible.map(\.id)
ScrollView {
VStack(alignment: .leading, spacing: 16) {
Toggle("Favorites only", isOn: $favoritesOnly)
.accessibilityIdentifier("favorites-filter")
Text("Drag to reorder. Hidden items keep their places.")
.font(.callout)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
VStack(spacing: 0) {
ForEach(visible) { item in
HStack {
Text(item.title)
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
.accessibilityIdentifier("row-" + item.id)
Menu {
Button("Move up") {
moveOne(item.id, down: false, ids: ids, filter: filter)
}
.disabled(item.id == ids.first)
Button("Move down") {
moveOne(item.id, down: true, ids: ids, filter: filter)
}
.disabled(item.id == ids.last)
} label: {
Image(systemName: "arrow.up.arrow.down")
.frame(minWidth: 44, minHeight: 44)
}
.accessibilityLabel("Reorder \(item.title)")
.accessibilityIdentifier("menu-" + item.id)
}
.padding(.vertical, 8)
.background(alignment: .bottom) { Divider() }
}
.reorderable()
}
.reorderContainer(for: ReadingItem.self) { difference in
let anchor: String?
switch difference.destination.position {
case .before(let id): anchor = id
case .end: anchor = nil
}
apply(sources: difference.sources, before: anchor,
ids: ids, filter: filter)
}
if moveRejected {
Text("The list changed. Please try that move again.")
.font(.callout)
.fixedSize(horizontal: false, vertical: true)
.accessibilityIdentifier("move-rejected")
}
}
.padding()
}
.navigationTitle("Reading")
}
private func apply(sources: [String], before anchor: String?,
ids: [String], filter: Bool) {
guard favoritesOnly == filter else {
moveRejected = true
return
}
moveRejected = !moveVisibleItems(
in: &items,
matching: { !filter || $0.isFavorite },
expectedIDs: ids, sources: sources, before: anchor
)
}
private func moveOne(_ id: String, down: Bool,
ids: [String], filter: Bool) {
guard let index = ids.firstIndex(of: id) else { return }
if down {
guard index + 1 < ids.count else { return }
let anchor = index + 2 < ids.count ? ids[index + 2] : nil
apply(sources: [id], before: anchor, ids: ids, filter: filter)
} else {
guard index > 0 else { return }
apply(sources: [id], before: ids[index - 1], ids: ids, filter: filter)
}
}
}
Moving down uses the row after the next row as the insertion anchor. Moving A down in A, C, E therefore means “put A before E,” producing C, A, E. For the final position, the anchor is nil.
The ID comparison protects an operation submitted with an outdated projection. It is not a promise that SwiftUI freezes this closure at the beginning of a drag. If your app needs to preserve precisely what the user saw at gesture start while live updates arrive, capture an explicit drag-session snapshot and define a refresh policy. Apple’s isEnabled parameter also lets you turn off reordering when another operation makes it inappropriate.
This demo handles one filtered collection. Moving across sections, accepting items from another app and persisting order each need their own rules. Our broader reordering overview covers the API’s other shapes.
Check what clearing the filter reveals
Run this last block from a synchronous test or debug function alongside the model:
var items = ReadingItem.examples
let accepted = moveVisibleItems(
in: &items,
matching: \.isFavorite,
expectedIDs: ["a", "c", "e"],
sources: ["e"],
before: "a"
)
precondition(accepted)
precondition(items.map(\.id) == ["e", "b", "a", "d", "c"])
let beforeStaleMove = items
let staleAccepted = moveVisibleItems(
in: &items,
matching: \.isFavorite,
expectedIDs: ["a", "c", "e"], // No longer the visible order.
sources: ["c"],
before: "e"
)
precondition(!staleAccepted)
precondition(items == beforeStaleMove)
The download also checks duplicate and missing IDs, changed filter membership, deleted rows, multiple moved items, preserved title edits, and a deliberate wrong-offset implementation. Exhaustive small-array checks verify that hidden values stay in their original slots, no IDs disappear, and both the moved and unmoved visible items retain their relative order.
Native iOS 27.2 simulator tests exercise dragging upward and to the end, clearing the filter, menu moves and large text. Both ordinary and MainActor-default builds compile with warnings treated as errors. These are simulator and model checks, not physical-device or full VoiceOver-session verification.
The useful acceptance test is simple: move a favorite, clear the filter, and check the whole list. A smooth animation only tells you where the row appeared to go. The full collection tells you what actually moved.