> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swiftui/view/grouping/foreach/.ondelete.md).

# .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 %}
