Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created December 11, 2021 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/502ad97755727de99d2991a44003313a to your computer and use it in GitHub Desktop.
Save rayfix/502ad97755727de99d2991a44003313a to your computer and use it in GitHub Desktop.
Using IdentifiedCollection package to manage large lists in SwiftUI
//
// ContentView.swift
// DemoLister
//
// Created by Ray Fix on 12/11/21.
//
import SwiftUI
import IdentifiedCollections
struct Todo: Identifiable {
var id: UUID
var name: String
var isCompleted: Bool
}
final class ViewModel: ObservableObject {
@Published var items: IdentifiedArrayOf<Todo>
init(count: Int) {
self.items = IdentifiedArrayOf<Todo>(uniqueElements:
(1...count).map {
Todo(id: UUID(), name: "Item \($0)", isCompleted: .random())
})
}
func toggleComplete(id: UUID) {
items[id: id]?.isCompleted.toggle()
print("ITEM \(items[id: id]!)")
}
}
struct ContentView: View {
@StateObject var viewModel = ViewModel(count: 1000)
var body: some View {
List(viewModel.items) { item in
HStack {
Text(item.name)
Toggle(item.isCompleted ? "Completed" : "Incomplete", isOn: .init(
get: { item.isCompleted },
set: { _ in viewModel.toggleComplete(id: item.id)}
)
).toggleStyle(.button)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment