通过功能使用手势时,键入"任何视图"不能符合"视图"



我正试图将我的手势提取到一个函数中,以便在我的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
            }
        })
    }
}

关键字some&anysome返回任何不变的Gesture类型,就像如果它是DragGesture一样,它应该总是这样。而any返回例如未被设置为总是DragGesture手势的Gesture的类型。

在您的情况下,用some替换any就可以了。

编辑:any更像是一个充当Type橡皮擦的演员。some表示关联类型,其作用更像泛型。有关更多信息,请查看此。

使用somesome指示编译器根据生成并返回的内容推断具体类型:

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

相关内容

最新更新