我正试图将我的手势提取到一个函数中,以便在我的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
&any
。some
返回任何不变的Gesture
类型,就像如果它是DragGesture
一样,它应该总是这样。而any返回例如未被设置为总是DragGesture
手势的Gesture
的类型。
在您的情况下,用some
替换any
就可以了。
编辑:any
更像是一个充当Type橡皮擦的演员。some
表示关联类型,其作用更像泛型。有关更多信息,请查看此。
使用some
,some
指示编译器根据生成并返回的内容推断具体类型:
func swipeDownGesture() -> some Gesture { // << here !!
DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ gesture in
if gesture.translation.height > 0 {
// Run some code
}
})
}