Reputation: 129
I got a problem. I need the value of the item that got deleted with the .onDelete function. I am new to swift and i have no clue how to do it. It would be nice if someone could help me out here. Thanks.
The List:
struct TimeStampList: View {
@EnvironmentObject var user: User
@ObservedObject var viewModel: SingleEntriesViewModel
var body: some View {
List {
ForEach(0..<self.viewModel.timeStamps.count, id: \.self) { timeStamp in
Section(header: Text("\(TimeStamp.convertToReadableString(date: self.viewModel.timeStamps[timeStamp].date))")) {
if (self.viewModel.timeStamps[timeStamp].dayType != "V") {
ForEach(self.viewModel.timeStamps[timeStamp].times, id: \.self) { time in
SingleEntriesRow(time: time, id: UUID())
}.onDelete { times in
self.deleteTimeStamps(timeStamp: timeStamp, row: times)
}
}
else {
Text("V")
}
}
}
}
}
func deleteTimeStamps(timeStamp: Int, row: IndexSet) {
self.viewModel.timeStamps[timeStamp].deleteTime(at: row)
self.viewModel.sortTimeStamps()
self.viewModel.timeStamps[timeStamp].times[row] // <- I need this but row is of type IndexSet not Int.
}
}
The TimeStamp:
struct TimeStamp: Identifiable {
var id = UUID()
var date: Date
var times: [String]
var dayType: String
}
The ViewModel:
class SingleEntriesViewModel: ObservableObject {
@Published var timeStamps = [TimeStamp]()
}
Upvotes: 1
Views: 145
Reputation: 54466
This is because IndexSet
is a collection of indices of type Int
.
You can either get the first index:
if let index = row.first {
// index is of type `Int`
// let result = self.viewModel.timeStamps[timeStamp].times[index]
}
or use a forEach
to iterate through all indices:
row.forEach { index in
// index is of type `Int`
// let result = self.viewModel.timeStamps[timeStamp].times[index]
}
Upvotes: 1