# .onDelete

[SwiftUI](/ios/swiftui.md) ⟩ [view](/ios/swiftui/view.md) ⟩ [groupings](/ios/swiftui/view/grouping.md) ⟩ [ForEach](/ios/swiftui/view/grouping/foreach.md) ⟩ .onDelete&#x20;

{% hint style="success" %}
Tell SwiftUI what to do <mark style="color:yellow;">when elements in the</mark> [ForEach](/ios/swiftui/view/grouping/foreach.md) <mark style="color:yellow;">view are deleted</mark>.
{% endhint %}

```swift
// list data from environment object
// (assume `data` is the environment object)
ForEach(data.creatures) { creature in 
    CreatureRow(creature: creature)
}
// ⭐️ when elements in the ForEach view are deleted
.onDelete { indexSet in 

    /// • SwiftUI passes a set of indices to the closure 
    ///   that’s relative to the dynamic view’s underlying collection of data.
    
    // ⭐️ delete corresponding items from the underlying collection of data
    data.creatures.remove(atOffsets: indexSet)
}
```

{% tabs %}
{% tab title="👥 相關" %}

* [view](/ios/swiftui/view.md) ⟩ [state](/ios/swiftui/view/state/value.md) ⟩ [delete item from list](/ios/swiftui/view/action/delete.md)
* [add item to list](/ios/swiftui/view/action/add-item-to-list.md)
  {% endtab %}

{% tab title="📘 手冊" %}
\*
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swiftui/view/grouping/foreach/.ondelete.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
