通过函数使用手势时,类型“任何视图”不能符合“视图”

Joe*_*tto 3 ios swift swiftui

我正在尝试将手势提取到一个函数中,以便在我的 Swift 包之一中使用。我遇到的问题是,当我尝试在我的视图之一上使用它时,它不再符合视图。

以下代码会产生此错误:Type 'any View' cannot conform to 'View'

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Placeholder")
        } 
        .gesture(swipeDownGesture())
    }

    func swipeDownGesture() -> any Gesture {
        DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ gesture in
            if gesture.translation.height > 0 {
                // Run some code
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 5

usesome相反,some指示编译器从内部生成和返回的内容推断具体类型:

func swipeDownGesture() -> some Gesture {   // << here !!
    DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ gesture in
        if gesture.translation.height > 0 {
            // Run some code
        }
    })
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*mmy 5

some关键字&之间有很多区别anysome返回任何Gesture不会改变的类型,就像如果它是 a DragGesture,它应该始终是那样。然而,any 返回的类型Gesture未设置为始终为DragGesture手势。

在你的情况下,替换anysome就可以了。

编辑: any更像是一个充当类型橡皮擦的演员。some用于关联类型,其作用更像泛型。欲了解更多信息,请查看内容。