Home > Blockchain >  Type 'any View' cannot conform to 'View' when using Gesture via function
Type 'any View' cannot conform to 'View' when using Gesture via function

Time:07-23

I'm trying to extract my gesture out to a function for use within one of my Swift Packages. The issue I'm having is that when I attempt to use it on one of my views, it doesn't conform to View anymore.

The following code produces this error: 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
            }
        })
    }
}

CodePudding user response:

use some instead, some indicates for compiler to infer concrete type from whatever is generated and returned inside:

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

CodePudding user response:

There is a lot of difference between the keywords some & any. some is returning any type of Gesture that doesn't change, like if it is a DragGesture, it should always be that. Whereas any returns a type of Gesture that is not set to always be DragGesture gesture for example.

In your case, replacing any with some does the trick.

Edit: any is more like a cast working as a Type eraser. some is for associated type, acting more like generics. For more info, check this out.

  • Related