Reputation: 568
i have this Code:
struct CreateInfo: Identifiable {
var id: String
var name: String
var time: String
var day: String
var isDeleted: Bool
}
struct ZettelView: View {
@State var zettelInfos = [CreateInfo]()
@State private var showingAlert = false
@State private var savedValueForDeleteFunction: CreateInfo
func createNewInfo() {
var arr = [[String]]()
arr = getZettelData()
for x in arr {
zettelInfos.append(CreateInfo(id: "\(x[0])", name: "\(x[1])", time: "\(x[2])", day: "\(x[3])", isDeleted: false))
}
self.executeThisAsyncThing = false
}
@State var executeThisAsyncThing: Bool = true
var body: some View {
DispatchQueue.main.async {
if self.executeThisAsyncThing {
self.createNewInfo()
}
}
return VStack {
//New - testing
NavigationView {
List {
ForEach(zettelInfos) { x in
NavigationLink(destination: zettelDetailView(uuid: x.id, info: x)) {
Text("\(x.id)")
}
}.onDelete(perform: delete)
}.navigationBarTitle("Einkaufszettel")
.navigationBarItems(trailing: Button(action: {
self.addRow()
}) {
Image(systemName: "plus.app.fill")
})
}
.alert(isPresented: $showingAlert) {
Alert(title: Text(" meImportantssage"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
}
}
}
func delete(at offsets: IndexSet) {
zettelInfos.remove(atOffsets: offsets)
self.showingAlert = true
}
private func addRow() {
let dateAndTime = Date()
let dfDay = DateFormatter()
let dfTime = DateFormatter()
dfDay.dateFormat = "dd.MM.yyyy"
dfTime.dateFormat = "HH:mm:ss"
let day = dfDay.string(from: dateAndTime)
let time = dfTime.string(from: dateAndTime)
let x = CreateInfo(id: UUID().uuidString, name: "Neuer Zettel", time: time, day: day, isDeleted: false)
saveZettelData(x: x)
zettelInfos.append(x)
}
}
So my question is, how can I parse my x variable in the ForEach to the delete func?
Why do I want this? -> the x variable in the foreach has a UUID and I need the UUID from the x
Does anyone of you know a way, how I can get the UUID from the x
?
This is my first App with swift and I am trying to learn it, but in some cases, its way different to other languages I know. normally I would parse a value to a delete function and then iterate through it to find and delete the specific row/data, but in swift its another way to go, I guess.
Upvotes: 1
Views: 316
Reputation: 257663
Here is a way to have it
func delete(at offsets: IndexSet) {
let index = offsets[offsets.startIndex]
let x = zettelInfos[index]
// ... do anything needed with x.id now
zettelInfos.remove(atOffsets: offsets)
self.showingAlert = true
}
Upvotes: 2