Steffen D. Sommer
Steffen D. Sommer

Reputation: 2926

Variable of type that conforms to protocol

I have a struct that conforms to a protocol. That protocol specifies a variable that needs to conform to another protocol. In my struct I want to declare that variable using a specific type that conforms to the needed protocol.

The code, which should make it a lot more clear:

protocol ViewModel {
    var isActive: Bool { get }
}

struct TestViewModel: ViewModel {
    var isActive = false
}


protocol View {
    var viewModel: ViewModel { get }
}

struct TestView: View {
    var viewModel: TestViewModel
}

Using the above code, I will get a compiler error saying that the type TestView does not conform to protocol View. I would have expected that since TestViewModel conforms to ViewModel, that this would be okay, but apparently not.

Is there any way I can do what I want? I need to have the viewModel type casted to TestViewModel when using it in my TestView.

Upvotes: 1

Views: 1040

Answers (1)

Roberto Frontado
Roberto Frontado

Reputation: 438

You need to work with generics (associatedtype in protocols)

protocol ViewModel {
    var isActive: Bool { get }
}

struct TestViewModel: ViewModel {
    var isActive = false
}

protocol View {
    associatedtype V: ViewModel
    var viewModel: V { get }
}

struct TestView: View {
    var viewModel: TestViewModel
}

This should works, you are telling to the struct that viewModel should be some class that implements ViewModel protocol

Upvotes: 3

Related Questions