"Function declares an opaque return type [...]" error when declaring a view as a variable inside the body of a View in SwiftUI

When modifying and building views, you can do this without a return statement and a building block one above the other without commas. This is called a multi-statement closure. When you try to create a variable inside a multi-statement closure, the compiler is going to complain because there is a mismatch in types (you can only combine views one after another, nothing more). See this answer for more details: https://stackoverflow.com/a/56435128/7715250

A way to fix this is to explicitly return the views you are combining, so you don't make use of the multi-closure statements:

struct MyView: View {
    var body: some View {
        let image = Image("Some image").shadow(radius: 10)
        let myRadius = image.modifier.radius

        // Do something with myRadius

        return image // No multi closure statements.
    }
}

If your view you want to reference is inside a stack, you should declare it outside the stack like this:

var body: some View {
    let myImage = Image("image").shadow(radius: 10)

    let stack = HStack {
        myImage
        Image("image2")
    }

    return stack
}

Tags:

Swift

Swiftui