gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
import SwiftUI struct Task: Identifiable { var text: String var id = UUID() } struct…
- User
import SwiftUI
struct Task: Identifiable { var text: String var id = UUID() }
struct ContentView: View { @State var task = "" @State var tasks: [Task] = []
func add() { if !task.isEmpty { tasks.append(Task(text: task)) task = "" } } var body: some View { VStack { HStack { TextField("New task…", text: $task) { _ in } onCommit: { add() } Button(action: add) { Image(systemName: "plus") .foregroundColor(.blue) } } .padding(8.0) List(tasks) { item in Text(item.text) .contextMenu { Button(action: { //delete the task with text which equals item.text from the tasks }) { Label("Delete", systemImage: "x.circle") } } } } }} #Preview { ContentView() }
- Assistant
To delete a task from the
tasksarray based on itstext, you can use theremoveAll(where:)method. Here's the updated code:struct Task: Identifiable { var text: String var id = UUID() } struct ContentView: View { @State var task = "" @State var tasks: [Task] = [] func add() { if !task.isEmpty { tasks.append(Task(text: task)) task = "" } } func deleteTask(withText text: String) { tasks.removeAll { $0.text == text } } var body: some View { VStack { HStack { TextField("New task…", text: $task) { _ in } onCommit: { add() } Button(action: add) { Image(systemName: "plus") .foregroundColor(.blue) } } .padding(8.0) List(tasks) { item in Text(item.text) .contextMenu { Button(action: { deleteTask(withText: item.text) }) { Label("Delete", systemImage: "x.circle") } } } } } } import SwiftUI struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }In the code snippet above, a new function
deleteTaskis added to handle deleting a task from thetasksarray. Inside thedeleteTaskfunction, theremoveAll(where:)method is used to remove all tasks that have atextvalue equal to the provided parametertext.Inside the
Listview, thedeleteTaskfunction is called with theitem.textas the parameter when the "Delete" action is triggered from the context menu.