Skip to content

Instantly share code, notes, and snippets.

@pitt500
Last active August 3, 2022 14:46
Show Gist options
  • Save pitt500/384de25a339735eb93250bc037d0905b to your computer and use it in GitHub Desktop.
Save pitt500/384de25a339735eb93250bc037d0905b to your computer and use it in GitHub Desktop.
For more context about this algorithm, check out this video: https://youtu.be/M3eJIo9h0fg
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 {
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")
}
}
// This sorting algorithm is not stable!
//func sort() {
// todos.sort { !$0.isComplete && $1.isComplete }
//}
//This is the fixed version!
func sort() {
todos = todos
.enumerated()
.sorted {
(!$0.element.isComplete && $1.element.isComplete)
|| ($0.offset < $1.offset)
}
.map(\.element)
}
}
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