🔹.onDelete
when elements in the ForEach view are deleted
SwiftUI ⟩ view ⟩ groupings ⟩ ForEach ⟩ .onDelete
Tell SwiftUI what to do when elements in the ForEach view are deleted.
// 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)
}Last updated
Was this helpful?