Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active October 14, 2021 00:08
Show Gist options
  • Save IanKeen/495279f7b46823a58b3dc24a2f3cdf64 to your computer and use it in GitHub Desktop.
Save IanKeen/495279f7b46823a58b3dc24a2f3cdf64 to your computer and use it in GitHub Desktop.
SwiftUI: quick and dirty nested ForEach debugger
import SwiftUI
struct Location: Equatable {
var file: String
var line: UInt
}
private struct ForEachKey: EnvironmentKey {
static var defaultValue: [Location] = []
}
private extension EnvironmentValues {
var forEachLocations: [Location] {
get { self[ForEachKey.self] }
set { self[ForEachKey.self] = newValue }
}
}
struct _ForEach<Data: RandomAccessCollection, ID, Content: View>: View where ID == Data.Element.ID, Data.Element: Identifiable {
@Environment(\.forEachLocations) private var forEachLocations
private let location: Location
private var data: Data
private var content: (Data.Element) -> Content
init(file: StaticString = #file, line: UInt = #line, _ data: Data, @ViewBuilder content: @escaping (Data.Element) -> Content) {
self.data = data
self.content = content
self.location = .init(file: "\(file)", line: line)
}
var body: some View {
ForEach(data) { element in
content(element)
.environment(\.forEachLocations, forEachLocations + [location])
}
.onAppear {
if !forEachLocations.isEmpty {
print("⚠️Nested ForEach @ \(location.file):\(location.line)")
for location in forEachLocations.reversed() {
print("Contained in: \(location.file):\(location.line)")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment