Godlike
Godlike

Reputation: 1928

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

Upvotes: 13

Views: 12556

Answers (3)

David Reich
David Reich

Reputation: 779

Extending Cristik's solution:

protocol ViewFactoryProtocol {
    func makeView(parameter: SomeType) -> AnyView
}

Upvotes: 1

Cristik
Cristik

Reputation: 32782

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.

Upvotes: 6

Kevin Tezlaf
Kevin Tezlaf

Reputation: 181

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 }
}

Upvotes: 16

Related Questions