Created
December 11, 2021 19:57
-
-
Save rayfix/502ad97755727de99d2991a44003313a to your computer and use it in GitHub Desktop.
Using IdentifiedCollection package to manage large lists in SwiftUI
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
// | |
// 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