# .onDelete

[SwiftUI](https://lochiwei.gitbook.io/ios/swiftui) ⟩ [view](https://lochiwei.gitbook.io/ios/swiftui/view) ⟩ [groupings](https://lochiwei.gitbook.io/ios/swiftui/view/grouping) ⟩ [ForEach](https://lochiwei.gitbook.io/ios/swiftui/view/grouping/foreach) ⟩ .onDelete&#x20;

{% hint style="success" %}
Tell SwiftUI what to do <mark style="color:yellow;">when elements in the</mark> [ForEach](https://lochiwei.gitbook.io/ios/swiftui/view/grouping/foreach) <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](https://lochiwei.gitbook.io/ios/swiftui/view) ⟩ [state](https://lochiwei.gitbook.io/ios/swiftui/view/state/value) ⟩ [delete](https://lochiwei.gitbook.io/ios/swiftui/view/action/delete "mention")
* [add-item-to-list](https://lochiwei.gitbook.io/ios/swiftui/view/action/add-item-to-list "mention")
  {% endtab %}

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