Skip to content

Instantly share code, notes, and snippets.

@profburke
Created November 17, 2021 00:05
Show Gist options
  • Save profburke/25c11b5eaa7f66fe128da33c909d6f50 to your computer and use it in GitHub Desktop.
Save profburke/25c11b5eaa7f66fe128da33c909d6f50 to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// SwiftUIDataManagingSample
//
// Created by Matthew Burke on 11/16/21.
//
import SwiftUI
struct ContentView: View {
@Binding var items: [Item]
var body: some View {
List {
ForEach(items) { item in
HStack {
Text(item.name)
Spacer()
Text("\(item.value)")
}
.onTapGesture {
var b = binding(for: item)
b.update()
}
}
}
.navigationTitle("Items")
}
func binding(for item: Item) -> Binding<Item> {
guard let index = items.firstIndex(where: { $0.id == item.id } ) else {
fatalError("Can't find item in array.")
}
return $items[index]
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ContentView(items: .constant(Item.items))
}
.preferredColorScheme(.light)
NavigationView {
ContentView(items: .constant(Item.items))
}
.preferredColorScheme(.dark)
}
}
//
// SwiftUIDataManagingSampleApp.swift
// SwiftUIDataManagingSample
//
// Created by Matthew Burke on 11/16/21.
//
import SwiftUI
@main
struct SwiftUIDataManagingSampleApp: App {
@State private var items = Item.items
var body: some Scene {
WindowGroup {
NavigationView {
ContentView(items: $items)
}
}
}
}
public struct Item: Identifiable {
public static var items = [
Item(name: "item 1"),
Item(name: "item 2"),
Item(name: "item 3"),
Item(name: "item 4"),
Item(name: "item 5"),
Item(name: "item 6"),
Item(name: "item 7"),
]
public var id: UUID = UUID()
public var value: Int
public let name: String
public init(name: String, value: Int = Int.random(in: 1...100)) {
self.name = name
self.value = value
}
public mutating func update() {
value = Int.random(in: 1...100)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment