Home > database >  Error expected : Ternary conditional nil for not optional type of parameter in SwiftUI function
Error expected : Ternary conditional nil for not optional type of parameter in SwiftUI function

Time:07-16

Code below works fine even if optional type isn't what the .gesture() modifier really wants for its parameter type.

someKindOfView
    .gesture(condition ? DragGesture() : nil)
 

Why is this possible?

Many thanks!!!!

CodePudding user response:

Because the Gesture is generic protocol...

demo1

and so the gesture modifier accepts generic type conforming to Gesture

demo2

and there is such extension confirming Optional to Gesture

demo3

so in case of

.gesture(condition ? DragGesture() : nil)

compiler infers type as .gesture(_ gesture: DragGesture?, ... and all works.

  • Related