Last active
October 15, 2024 06:22
-
-
Save xmollv/e682ad6c22ac0bfd4b410e9fdb6db5c4 to your computer and use it in GitHub Desktop.
SwiftData + List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
If you're on Xcode 16, make sure to enable `SWIFT_ENABLE_OPAQUE_TYPE_ERASURE=NO` | |
to work around the performance issues of Debug builds: https://indieweb.social/@curtclifton/113273571392595819 | |
*/ | |
import SwiftUI | |
import SwiftData | |
@main | |
struct SlowDataApp: App { | |
var sharedModelContainer: ModelContainer = { | |
let schema = Schema([Item.self]) | |
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) | |
return try! ModelContainer(for: schema, configurations: [modelConfiguration]) | |
}() | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
.modelContainer(sharedModelContainer) | |
} | |
} | |
struct ContentView: View { | |
@Environment(\.modelContext) private var modelContext | |
@State var selection: Menu? = .optionA | |
var body: some View { | |
NavigationSplitView { | |
List(Menu.allCases, selection: $selection) { menu in | |
Text(menu.rawValue).tag(menu) | |
} | |
} detail: { | |
DemoListView(selectedMenu: $selection) | |
}.onAppear { | |
// Do this just once | |
// (0..<15_000).forEach { index in | |
// let item = Item() | |
// modelContext.insert(item) | |
// } | |
} | |
} | |
} | |
struct DemoListView: View { | |
@Binding var selectedMenu: Menu? | |
@Query private var items: [Item] | |
init(selectedMenu: Binding<Menu?>) { | |
self._selectedMenu = selectedMenu | |
self._items = Query(filter: selectedMenu.wrappedValue?.predicate) | |
} | |
var body: some View { | |
List(items) { item in | |
ListRowView(item: item) | |
} | |
.navigationTitle(selectedMenu?.rawValue ?? "N/A") | |
} | |
} | |
struct ListRowView: View { | |
let item: Item | |
var body: some View { | |
Text(item.isOptionA ? "Option A" : "Option B") | |
} | |
} | |
enum Menu: String, CaseIterable, Hashable, Identifiable { | |
var id: String { rawValue } | |
case optionA | |
case optionB | |
case all | |
var predicate: Predicate<Item> { | |
switch self { | |
case .optionA: return #Predicate { $0.isOptionA } | |
case .optionB: return #Predicate { !$0.isOptionA } | |
case .all: return #Predicate { _ in true } | |
} | |
} | |
} | |
@Model final class Item: Identifiable { | |
var isOptionA: Bool | |
init() { | |
self.isOptionA = Bool.random() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment