Print inside View in SwiftUI – Type ‘()’ cannot conform to ‘View’
I can assume that you have faced this error while trying to add a print statement in your SwiftUI View to debug your code.
I have got the same error: Type '()' cannot conform to 'View'
Then, I realized that SwiftUI won’t allow me to use print statements directly into my View.
So, I found a solution that can actually let me use print()
.
For example:
import SwiftUI struct ContentView: View { @State private var number = 3 var body: some View { print(number) } }
I will get an error like this:
How to fix: Type ‘()’ cannot conform to ‘View’
Just use a variable or constant and print there just like this:
import SwiftUI struct ContentView: View { @State private var number = 3 var body: some View { let a = print(number) } }
It should work fine but you will get a warning from Xcode: Constant 'a' inferred to have type '()', which may be unexpected
We can simply use an underscore to get rid of this warning: let _ = print(number)
Using a var or let will solve your problem.
In my case, it solved the error properly and I could use print statements in my View to debug my code.
But when I started writing this tutorial, I found another issue. If I use only print statement in my View then it will not print in my console debug.
To print it I need at least one element in my SwiftUI view.
This will work:
import SwiftUI struct ContentView: View { @State private var number = 3 var body: some View { let _ = print(number) Text("hi") } }
Note: print will work fine in Button action.
Leave a Reply