SwiftUI: Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

G. Abhisek
2 min readJul 23, 2020

While writing SwiftUI views, you might quickly come across an error which says

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

When does such an error happen?

A view body in SwiftUI goes like

var body: some View {
Text("Hello, World!")
}

The body is a computed property returning an Opaque type of a View type. The compiler does not need to have a return type explicitly set as it can infer the return type. The error that you have encountered could have happened because of the following reasons:

The body does not have a return type

var body: some View {
let displayText = "Heyy Swifters !!"
Text(displayText)
}

To fix this we just add a simple return type to help the compiler infer the type of the body.

A conditional body involving multiple views

var body: some View {
if isSwiftyDisplay {
Text("Heyy Swifters!!")
} else {
Text("Hello World!!")
}
}

Here you have two ways to fix this, one is you add return statement to both the views or add @ViewBuilder property wrapper.

@ViewBuilder
var
body: some View {
if isSwiftyDisplay {
Text("Heyy Swifters!!")
} else {
Text("Hello World!!")
}
}

The body having multiple views

var body: some View {
Text("Heyy Swifters!!")
Text("Hello World!!")
}

To fix this you can specify a way to club the views together by using either one of HStack, ZStack and VStack as per requirement.

--

--