NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Is there an easy way to find the index in an array from ForEach

Forums > Swift

Say I have this ForEach:

ForEach($tortoises.items, id: \.name){ $item in
                                    Text("Name: \(")

                                        tortoises.items.remove(at: ) // What do I put here?

What do I put next to the "at:" i think it needs to be the Index of where it is in the array but how do I get that?

Thankyou in advance!


I think this is the way to do that:

ForEach(0 ..< tortoises.items.count) {
    tortoises.items.remove(at: $0)


ForEach(0 ..< tortoises.items.count) {
tortoises.items.remove(at: $0)

You don't actually want to do it that way because looping over a range like that is for constant data, meaning when you remove items from the array, you'll crash because the number of items has changed from what ForEach expects. Also, you lose the binding to the item that is passed as a parameter to the ForEach.

You could use enumerated to get the items and their indices, but the better way to do it would be to just use firstIndex(of:) to grab the index of the item and then use it in remove(at:).

    if let idx = tortoises.items.firstIndex(of: item) {
        tortoises.items.remove(at: idx)


You may be confusing yourself by combining two different concepts.

  1. ForEach is a view building factory. Its job is to build a view for each item you provide it.
  2. Deleting items in an array. This is separate from building views.

Keep these two concepts separate.

Concept 1
If you have an array with 8 items in it, ForEach will build 8 views.
If you have an array with 3 items in it, ForEach will build 3 views for you.

Concept 2
If you have an array with 8 items in it, and want to delete item 2, then delete item 2.
If you have an array with 3 items in it, and want to delete the first item, then delete the first item.

So re-ask your question.

You're telling the ForEach that you have a number of objects in an array named tortoises.items. You're also noting that the makes each object unique.

So is there an array function that can return the first item in the array with that unique name?

See --> Swift Arrary Documentation


Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.