Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UI use View in a Protocol (Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements)

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 :)

like image 886
Godlike Avatar asked Dec 18 '22 14:12

Godlike


2 Answers

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 }
}
like image 98
Kevin Tezlaf Avatar answered Jan 14 '23 08:01

Kevin Tezlaf


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.

like image 24
Cristik Avatar answered Jan 14 '23 06:01

Cristik