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

Tam*_*gel 14 swift swiftui

Assume I have a View with an Image that has a shadow property:

struct ContentView: View {
    var body: some View {
        Image("turtlerock").shadow(radius: 10)
    }
}
Run Code Online (Sandbox Code Playgroud)

Now imagine I want to access the value of the shadow radius. I assumed I could do this:

struct ContentView: View {
    var body: some View {
        let myImage = Image("turtlerock").shadow(radius: 10)
        print(myImage.modifier.radius)
    }
}
Run Code Online (Sandbox Code Playgroud)

However, this returns an error:

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

Is there a way to accomplish this somehow?

J. *_*Doe 22

在修改和构建视图时,您可以在没有return语句的情况下执行此操作,而在另一个语句之上不加逗号的情况下可以使用构建块。这称为多语句闭包。当您尝试在多语句闭包中创建变量时,编译器会抱怨,因为类型不匹配(您只能一个接一个地合并视图,仅此而已)。请参阅此答案以获取更多详细信息:https : //stackoverflow.com/a/56435128/7715250

解决此问题的一种方法是显式返回要合并的视图,因此您不必使用多闭包语句:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)