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.
struct ContentView: View {
@State var name: String = ""
var body: some View {
name = "Angela"
Text(name)
}
}
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.
@State var name: String = "Angela"
var body: some View {
Text(name)
}
Use the .onAppear
modifier to do something when a SwiftUI view appears. The following code changes the name correctly:
var body: some View {
Text(name)
.onAppear {
name = "Angela"
}
}
You can also make the error go away by adding a return
statement to explicitly return a view.
var body: some View {
name = “Angela”
return Text(name)
}
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.