Skip to content

Instantly share code, notes, and snippets.

@xmollv
Created October 15, 2024 06:26
Show Gist options
  • Save xmollv/43a2939e421ce0f093f8bd198b99b120 to your computer and use it in GitHub Desktop.
Save xmollv/43a2939e421ce0f093f8bd198b99b120 to your computer and use it in GitHub Desktop.
Faster list test
/*
---------
THIS ONE DOESN'T FETCH FROM CORE DATA
---------
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 items: [Item] = (0...15_000).map { _ in Item() }
var body: some View {
NavigationSplitView {
List(Menu.allCases, selection: $selection) { menu in
Text(menu.rawValue).tag(menu)
}
} detail: {
DemoListView(selectedMenu: $selection, items: items)
}.onAppear {
// Do this just once
// (0..<15_000).forEach { index in
// let item = Item()
// modelContext.insert(item)
// }
}
}
}
struct DemoListView: View {
@Binding var selectedMenu: Menu?
var items: [Item]
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