Fixing the Type () cannot conform to View Error in Swift

Why am I getting this error?

You are trying to do something inside the body of a SwiftUI view besides displaying views. Placing print statements in a SwiftUI view will give you this error. Using if statements to conditionally show a view may also generate this error.

Let’s look at a simple example that shows a name in a SwiftUI Text label.

The code in the example is trying to set the name to show inside the body computed property. But you can’t run arbitrary code, such as setting a variable’s value, inside the body property. The body property must return a SwiftUI view so the code generates the Type () cannot conform to View error.

Ways to fix the error

The easiest way to fix the error in the example is to set the name when creating the name variable.

Use the .onAppear modifier to do something when a SwiftUI view appears. The following code changes the name correctly:

You can also make the error go away by adding a return statement to explicitly return a view.

Remove print statements from your SwiftUI views. If you need to print something to debug your app, use Xcode breakpoint actions to print to Xcode’s console.

If you need to do something in a SwiftUI view, move the code out of the body property to a separate function and call the function in the view.

Do you want to learn how to fix errors in your Swift code?

I’m writing a book, Fixing Swift Code, that will teach you how to find and fix errors in your Swift code so your projects will build successfully and run without crashing. Some of the things you’ll learn in the book include the following:

  • What Xcode’s build error messages really mean
  • How to fix your code so your project builds
  • How to find where your app crashes
  • The most common causes of app crashes and how to fix them

You can learn more about the book and get a discount on the book when it ships by going to the book’s homepage.