Type ‘()’ cannot conform to ‘View’ or how to use print() inside SwiftUI View


Greetings, traveler!

Most of us sometimes use print for debugging. But if we place this method inside a SwiftUI View, we will achieve this error:

Type ‘()’ cannot conform to ‘View’

There are several ways to handle this issue.

print()

Just assign this method as the constant’s value. It will be called during every render event.

struct SwiftUIView: View {
    
    var body: some View {
        
        let _ = print("Hello there!")
        
        Button("Button") {}
    }
    
}

_printChanges()

Use View’s static _printChanges method. This method will print out all View’s changes in the console.

struct SwiftUIView: View {
    
    @State private var value = 0
    
    var body: some View {
        
        let _ = Self._printChanges()
        
        Button(value.formatted()) {
            value += 1
        }
    }
    
}

onAppear

You can print anything without using constants inside the onAppear method closure.

struct SwiftUIView: View {
    
    @State private var value = 0
    
    var body: some View {
        
        Button(value.formatted()) {
            value += 1
        }
        .onAppear {
            print(value)
        }
    }
    
}

Conclusion

While Xcode offers a rich range of debugging tools, printing values remains one of the most convenient methods.