Home > Software engineering >  For SwiftUI Gestures: Function declares an opaque return type, but the return statements in its body
For SwiftUI Gestures: Function declares an opaque return type, but the return statements in its body

Time:07-23

I've received that error message for views, and I typically did @Viewbuilder or wrapped in AnyView. However, that won't work here because we have a gesture; how can I solve the problem for gestures? I tried AnyGesture to no avail.

 @State private var steadyStateEmojiZoomScale: CGFloat = 1
    @GestureState private var emojiZoomScale: CGFloat = 1
    
    private func pinchGesture() -> some Gesture {
        if selectedEmojis.count == 0 {
            return zoomGesture()
        } else {
            return MagnificationGesture()
                .updating($emojiZoomScale) { latestGestureScale, emojiZoomScale, _ in
                    emojiZoomScale = latestGestureScale
                }
                .onEnded { gestureScaleAtEnd in
                    steadyStateEmojiZoomScale *= gestureScaleAtEnd
                }
        }
    }

CodePudding user response:

Assuming that not provided zoomGesture has same value as magnification gesture (otherwise it would not be operable in any case) the fixed variant can be as follows

private func pinchGesture() -> AnyGesture<CGFloat> {
    if selectedEmojis.count == 0 {
        return AnyGesture(zoomGesture())
    } else {
        return AnyGesture(MagnificationGesture()
            .updating($emojiZoomScale) { latestGestureScale, emojiZoomScale, _ in
                emojiZoomScale = latestGestureScale
            }
            .onEnded { gestureScaleAtEnd in
                steadyStateEmojiZoomScale *= gestureScaleAtEnd
            })
    }
}

alternate is to break this on two separated gesture properties and use condition within view hierarchy to have advantage of ViewBuilder

  • Related