Last active
February 17, 2023 15:27
-
-
Save JohnSundell/73b4b6b9d999ff920e9e2e801120be22 to your computer and use it in GitHub Desktop.
Example view model class used during my Advanced SwiftUI workshop
This file contains 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
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