Skip to content

Instantly share code, notes, and snippets.

@garrettmurray
Last active February 1, 2024 01:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garrettmurray/4ec47079c97ff2fc64d63f735fa28c48 to your computer and use it in GitHub Desktop.
Save garrettmurray/4ec47079c97ff2fc64d63f735fa28c48 to your computer and use it in GitHub Desktop.
An example solution for .onDelete issues with nested sections of data in SwiftUI. Thanks to @mayoff for help!
import SwiftUI
func bind<Value, Answer>(_ value: Value, to answer: (Value) -> Answer) -> Answer { answer(value) }
struct Example: View {
struct SomeGroup: Identifiable, RandomAccessCollection {
typealias Indices = CountableRange<Int>
public typealias Index = Int;
var id: Int
var displayName: String
var numbers: [Int]
public var endIndex: Index {
return numbers.count - 1
}
public var startIndex: Index{
return 0
}
public subscript(position: Int) -> Int {
get { return numbers[position] }
set { numbers[position] = newValue }
}
}
var someGroups: [SomeGroup] = {
return [
SomeGroup(id: 0, displayName: "First", numbers: [1, 2, 3, 4]),
SomeGroup(id: 1, displayName: "Second", numbers: [1, 3, 5, 7])
]
}()
var body: some View {
List {
ForEach(someGroups.indices) { section in
bind(self.someGroups[section]) { someGroup in
Section(header: Text(someGroup.displayName)) {
ForEach(someGroup.numbers) { number in
Text("\(number)")
}
.onDelete { self.delete(at: $0, in: section) }
}
}
}
}
.listStyle(.grouped)
}
func delete(at offsets: IndexSet, in section: Int) {
print("\(section), \(offsets.first!)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment