1

I have an array of five different types of fruit names. I have a list which displays this array. When I .onDelete a fruit, I want to obtain the integer reflecting the row in the list which that certain fruit is on (right now I'm not concerned with actually deleting the fruit from the list). So for example, banana would be on row 1, apple would be on row 2, etc. Is there a way to obtain this integer using some function of IndexSet?

Here's the code:

var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]

List {
            ForEach(fruits) {fruit in
                Text(fruit)
            }
            .onDelete(perform: obtainingTheRowNumber)
}

func obtainingTheRowNumber(indexSet: IndexSet) -> Int {
//I want this function to return the row number of the object being deleted but I'm not sure how. 
}

I've tried looking into the documentation around IndexSet but I couldn't find anything and I feel like I'm missing something super simple.

Sutton
  • 53
  • 3
  • Does this answer your question? [ForEach - print both an item and numerical value](https://stackoverflow.com/questions/72222014/foreach-print-both-an-item-and-numerical-value) – lorem ipsum Dec 14 '22 at 12:46

2 Answers2

0

You can use this below code...

func obtainingTheRowNumber(indexSet: IndexSet){
        let index = indexSet[indexSet.startIndex] // get index from here
        print(index) 
    }
0
struct ContentView: View {
   
    var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]

    var body: some View {
        List {
            ForEach(fruits, id:\.self) {fruit in
                        Text(fruit)
                    
                    }
                    .onDelete(perform: obtainingTheRowNumber)
        }

        
        
   
    }
    
    func obtainingTheRowNumber(indexSet: IndexSet)   {
        for index in indexSet {
            print(index + 1)
        }
    }
        
}
multiverse
  • 425
  • 3
  • 13