Created
January 26, 2021 00:10
-
-
Save jeffreybergier/587c7cf109d65eb7ecff29779d43119a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// | |
// SwiftUI.List appears to iterate all the way including the endIndex | |
// which causes a crash. LazyVStack and ForEach do not do have this issue | |
// | |
// Refer to other GIST where there is no backing storage for the custom collection | |
// https://gist.github.com/jeffreybergier/0a366e173a871c1a8f3828824dbf7a54 | |
// | |
import SwiftUI | |
@main | |
struct BoomApp: App { | |
var body: some Scene { | |
WindowGroup { | |
NavigationView { | |
// Fill the left column of the split view | |
Color.clear | |
// Fill the right column | |
ContentView() | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
@StateObject var data = ObservableCollection() | |
var body: some View { | |
/// LazyVStack and ForEach work fine | |
/// This appears to be an issue with list | |
// LazyVStack { | |
// ForEach(self.data) { boom in | |
// Text("\(boom.id)") | |
// } | |
// } | |
List(self.data) { boom in | |
Text("\(boom.id)") | |
} | |
.toolbar { | |
ToolbarItem { | |
Button("Grow") { | |
self.data.grow() | |
} | |
} | |
ToolbarItem { | |
Button("Shrink") { | |
// This causes a crash | |
self.data.shrink() | |
} | |
} | |
} | |
} | |
} | |
struct Boom: Hashable, Identifiable { | |
var id: Int | |
init(_ id: Int) { | |
self.id = id | |
} | |
} | |
class ObservableCollection: RandomAccessCollection, ObservableObject { | |
private var storage: [Boom] = [] | |
func grow() { | |
self.objectWillChange.send() | |
self.storage.append(Boom(self.storage.count)) | |
} | |
func shrink() { | |
guard self.storage.isEmpty == false else { return } | |
self.objectWillChange.send() | |
self.storage.removeLast() | |
} | |
typealias Index = Int | |
typealias Element = Boom | |
var startIndex: Index { self.storage.startIndex } | |
var endIndex: Index { self.storage.endIndex } | |
subscript(index: Index) -> Iterator.Element { self.storage[index] } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment