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

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:

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.

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!!")
}
}
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.

--

--

Software Developer(iOS), Speaker & Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store