So I tried to put a print statement while debugging in a SwiftUI View.
print(\"landmark: \\(landmark)\")
In the following body.
<
It can be generalized to:
extension View {
func Perform(_ block: () -> Void) -> some View {
block()
return EmptyView()
}
}
So in your example:
ForEach(landmarkData) { landmark in
Perform { print("landmark: \(landmark)") }
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
You can print in the body structure but to do so you have to explcitly return the view you want to render. Normally in SwiftUI, the body property implicitly returns the view. For example, this will throw an error when you try to print:
struct SomeView: View {
@State var isOpen = false
var body: some View {
print(isOpen) // error thrown here
VStack {
// other view code
|
}
}
But if we explicitly return the view we want then it will work e.g.
struct SomeView: View {
@State var isOpen = false
var body: some View {
print(isOpen) // this ok because we explicitly returned the view below
// Notice the added 'return' below
return VStack {
// other view code
}
}
}
The above will work well if you're looking to view how state or environment objects are changing before returning your view, but if you want to print something deeper down within the view you are trying to return, then I would go with @Rok Krulec answer.
Very easy way to debug your Preview:
- Open your Swift project in Xcode 11.
- Right-click (or Control-click) on the Live Preview button in the bottom right corner of the preview.
- Select Debug Preview.
How to debug your SwiftUI previews in Xcode