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"))
}
}
Compiler errors out:
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?
Press ⇧⌘Y or choose View > Debug Area > Show Debug Area to show the console output (or ⇧⌘C / Activate Console). Usually, this window will open automatically when your program produces output (this is controlled by the Behaviors section of Xcode's Preferences).
Use print statement inside SwiftUI view You need to assign print() to a variable ( var ) or a constant ( let ). Here is an example of how we can use print() in a SwiftUI view. Text("Hello, World!") 1 and 2 We don't use the returning result ( x and y ) anywhere.
In Swift, you can print a variable or a constant to the screen using the print() function.
At least in Xcode 12/Swift 5.3, you can easily add a print statement anywhere in a function builder by simply storing its return value in a wildcard, effectively ignoring it:
let _ = print("hi!")
No setup or other verbosity needed!
Here's a helper Print( ... )
View that acts like a print( ... )
function but within a View
Put this in any of your view files
extension View {
func Print(_ vars: Any...) -> some View {
for v in vars { print(v) }
return EmptyView()
}
}
and use inside of body
like so
Print("Here I am", varOne, varTwo ...)
or inside a ForEach {}
like so
self.Print("Inside ForEach", varOne, varTwo ...)
Note: you might need to put Print()
into a Group {}
when combining with existing views
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With