So I tried to put a print statement while debugging in a SwiftUI View.
print("landmark: \(landmark)")
In the following body.
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Favorite only")
}
ForEach(landmarkData) { landmark in
print("landmark: \(landmark)")
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
So, what is the proper way to print to console in SwiftUI?
EDIT: I made Landmark conform to CustomStringConvertible:
struct Landmark: Hashable, Codable, Identifiable, CustomStringConvertible {
var description: String { name+"\(id)" }
var id: Int
var name: String
.....
I still get the "String is not convertible to any" error. Should it work now?
You can't because you're in a computed property. You need for example a button and in the action you define the print. Or work with breakpoints
It is possible to use print() remembering that all SwiftUI View content are (a) implicit closures and (b) it is highly recommended to decompose views as much as possible to have simple structure, so it might look like the following...
... and right clicking in Preview to select run as Debug Preview we get:
Here's a helper
Print( ... )
View that acts like aprint( ... )
function but within a ViewPut this in any of your view files
and use inside of
body
like soor inside a
ForEach {}
like soNote: you might need to put
Print()
into aGroup {}
when combining with existing viewsYou 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:
But if we explicitly return the view we want then it will work e.g.
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.
Try right-clicking on the live preview play button and selecting 'Debug Preview from the popup
You can not print in body structure i.e. a structure which is some view type.For print you need to make function out of body structure and call it using button or something else.