Last active
April 10, 2020 13:11
-
-
Save danhalliday/93dc96ae5a94767ece36d30dc707a545 to your computer and use it in GitHub Desktop.
SwiftUI Data Flow Buggy Example
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 Person { | |
let id: UUID | |
var name: String | |
var score: Float | |
} | |
class PersonStore: ObservableObject { | |
@Published var people: [Person] = [ | |
.init(id: .init(), name: "Joe", score: 1), | |
.init(id: .init(), name: "Jane", score: 5), | |
.init(id: .init(), name: "John", score: 10) | |
] | |
func add() { | |
people.append(.init(id: .init(), name: "New Person", score: 0)) | |
} | |
} | |
struct ContentView: View { | |
@EnvironmentObject var store: PersonStore | |
var body: some View { | |
NavigationView { | |
List { | |
ForEach(store.people.indexed(), id: \.1.id) { index, person in | |
NavigationLink(destination: EditView(person: self.$store.people[index])) { | |
RowView(person: person) | |
} | |
} | |
Button(action: store.add) { | |
Text("Add Person") | |
} | |
} | |
.listStyle(SidebarListStyle()) | |
} | |
} | |
} | |
struct RowView: View { | |
let person: Person | |
var body: some View { | |
Text("\(person.name) (\(person.score))") | |
} | |
} | |
struct EditView: View { | |
@Binding var person: Person | |
var body: some View { | |
VStack { | |
Text(person.name) | |
Text("\(person.score)") | |
TextField("Name", text: $person.name) | |
Slider(value: $person.score, in: 0...100) | |
} | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
} | |
} | |
extension Sequence { | |
func indexed() -> Array<(offset: Int, element: Element)> { | |
return Array(enumerated()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment