Last active
August 3, 2022 14:46
-
-
Save pitt500/2691fb59702d4cbf264b4977b9852dfa to your computer and use it in GitHub Desktop.
For more context about this code, check out this video: https://youtu.be/Yk-KPDa4w8E
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 Todo: Identifiable { | |
let id: UUID | |
var title = "Untitled" | |
var isComplete = false | |
static var sample: [Todo] { | |
[ | |
Todo( | |
id: UUID(), | |
title: "Milk", | |
isComplete: false | |
), | |
Todo( | |
id: UUID(), | |
title: "Buy eggs", | |
isComplete: false | |
), | |
Todo( | |
id: UUID(), | |
title: "Clean room", | |
isComplete: true | |
) | |
] | |
} | |
} | |
struct ContentView: View { | |
@State private var todos = Todo.sample | |
var body: some View { | |
NavigationView { | |
// When you need to mutate the elements on a collection inside a list, use binding objects | |
// DO NOT use indices. That approach is fragile. | |
List($todos) { $todo in | |
HStack { | |
Button { | |
withAnimation { | |
todo.isComplete.toggle() | |
sort() | |
} | |
} label: { | |
Image(systemName: todo.isComplete ? "checkmark.square" : "square") | |
} | |
Text(todo.title) | |
} | |
.foregroundColor(todo.isComplete ? .gray : nil) | |
} | |
.toolbar { | |
ToolbarItem(placement: .navigationBarTrailing) { | |
Button { | |
withAnimation { todos.append(Todo(id: UUID())) } | |
} label: { | |
Text("Add") | |
} | |
} | |
} | |
.navigationTitle("Todo List") | |
} | |
} | |
func sort() { | |
// There is something wrong on this algorithm, Can you spot what it is? | |
todos.sort { !$0.isComplete && $1.isComplete } | |
} | |
} | |
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