> 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/action/delete.md).

# delete item from list

[SwiftUI](/ios/swiftui.md) ⟩ [view](/ios/swiftui/view.md) ⟩ [state](/ios/swiftui/view/state/value.md) ⟩ [actions](/ios/swiftui/view/action.md) ⟩ delete item from list&#x20;

{% hint style="success" %}

1. add [.onDelete](/ios/swiftui/view/grouping/foreach/.ondelete.md) to [ForEach](/ios/swiftui/view/grouping/foreach.md).：when elements in the ForEach view are deleted
2. delete item from the underlying collection of data (in the action closure).
   {% 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="👥 相關" %}

* [ForEach](/ios/swiftui/view/grouping/foreach.md) ⟩ [.onDelete](/ios/swiftui/view/grouping/foreach/.ondelete.md)
  {% endtab %}

{% tab title="📘 手冊" %}

* [SwiftUI](https://developer.apple.com/documentation/swiftui) ⟩ [View groupings](https://developer.apple.com/documentation/swiftui/view-groupings) ⟩ [DynamicViewContent](https://developer.apple.com/documentation/swiftui/dynamicviewcontent) ⟩ [.onDelete(perform:)](https://developer.apple.com/documentation/swiftui/dynamicviewcontent/ondelete\(perform:\))
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] Hacking with Swift ⟩ [Deleting items using onDelete()](https://www.hackingwithswift.com/books/ios-swiftui/deleting-items-using-ondelete)&#x20;
  {% endtab %}
  {% endtabs %}
