๐Ÿ”ฐdelete item from list

SwiftUI โŸฉ view โŸฉ state โŸฉ actions โŸฉ delete item from list

  1. add .onDelete to ForEach.๏ผšwhen elements in the ForEach view are deleted

  2. delete item from the underlying collection of data (in the action closure).

// 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