I want to use View in a Protocol.
protocol Test {
var view: View { get }
}
Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
I just want to do the same thing as with my ViewController. Any idea?
protocol Test {
var viewController: UIViewController { get }
}
If I use an associated type, I get the error in my other protocols.
protocol Test2: Test {
//STUB
}
Any idea how to solve this problem? Thanks :)
SwiftUI.View is a protocol, and because it uses Self
(for example, in its body property), you cannot directly declare a property type as a View
.
You can define an associated type on Test
and constrain that type to be a View
:
protocol Test {
associatedtype T: View
var view: T { get }
}
You can't directly use the protocol unless you declare it as associated type, but you can use the type erased AnyView
instead:
protocol Test {
var view: AnyView { get }
}
Creating an AnyView
instance might add some noise in the code, however it's easy to create.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With