“Generic parameter could not be inferred” in SwiftUI UIViewRepresentable

后端 未结 2 1051
别那么骄傲
别那么骄傲 2021-01-14 07:25

I\'ve got the following code, which makes it possible to use the UIKit\'s UIScrollView in my SwiftUI code. It can be pasted in a new SwiftUI project.

         


        
2条回答
  •  执念已碎
    2021-01-14 08:09

    I disagree with your assertion that the enum should be nested inside the class for the following reasons:

    • The enum is intended to be used both inside and outside of the class, with a generic type being required in order to use it.
    • The enum does not make use of, and therefore has no dependency on, the generic Content type.
    • With a good enough name, the intended use of the enum would be obvious.

    If you really want to nest the enum definition, I would suggest the following:

    • Drop the generic type requirement on the class definition,
    • Convert your content member to be of AnyView type,
    • Make your init functions generic and store the return values of the given view builders into type-erased views, like so:
    init(@ViewBuilder content: () -> Content) {
        self._action = Binding.constant(Action.idle)
        self.content = AnyView(content())
    }
    
    init(action: Binding, @ViewBuilder content: () -> Content) {
        self._action = action
        self.content = AnyView(content())
    }
    
    

    Of course, with this approach, you will:

    • Lose the type information of the underlying content view.
    • Possibly incur a greater runtime cost with type-erased views.

    So it depends what you value more in this case... Ahhh, tradeoffs...

提交回复
热议问题