Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Last active February 17, 2023 15:27
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 JohnSundell/73b4b6b9d999ff920e9e2e801120be22 to your computer and use it in GitHub Desktop.
Save JohnSundell/73b4b6b9d999ff920e9e2e801120be22 to your computer and use it in GitHub Desktop.
Example view model class used during my Advanced SwiftUI workshop
import SwiftUI
struct Item: Equatable, Identifiable {
let id = UUID()
var title: String
var isFavorite = false
}
@MainActor class ListViewModel: ObservableObject {
@Published private(set) var items: [Item] = []
private var isLoadingMoreItems = false
init() {
addItems()
}
func loadMoreItems() {
guard !isLoadingMoreItems else { return }
isLoadingMoreItems = true
Task {
try! await Task.sleep(nanoseconds: 1_000_000_000)
addItems()
isLoadingMoreItems = false
}
}
func toggleFavorite(forItem item: Item) async throws {
try await Task.sleep(nanoseconds: 1_000_000_000)
guard let index = items.firstIndex(where: { $0.id == item.id }) else {
return
}
items[index].isFavorite.toggle()
}
private func addItems() {
items += (items.count..<items.count + 50).map { index in
Item(title: "Item \(index)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment