Reputation: 22986
I want to show SwiftUI View
s as subview of a UIViewController
. These views must implement a protocol.
I have this:
protocol ContentViewProtocol : View
{
var values: [CGFloat] { get }
}
...
import SwiftUI
struct SearchContentView : ContentViewProtocol
{
var values: [CGFloat] = [0.5, 0.7]
var body: some View
{
VStack
{
...
}
}
}
...
func showContent(view: ContentViewProtocol) <=== ERROR
{
var child = UIHostingController(rootView: view) <=== SAME ERROR
...
}
I get the following error: Protocol 'ContentViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements
I get the same error when using a plain View
as function parameter type (so with func showContent(view: View)
).
How can I prevent this?
Upvotes: 2
Views: 2043
Reputation: 273968
You can do what the error says, and use ContentViewProtocol
as a generic constraint. Make showContent
generic:
func showContent<V: ContentViewProtocol>(view: V)
{
let child = UIHostingController(rootView: view)
...
}
Upvotes: 2