Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SwiftUI views with protocol interfaces to view models.
import SwiftUI
/// View model protocol
protocol ViewModel: ObservableObject {
var count: Int { get }
func increase()
}
/// Concrete implementation
class MyViewModel: ViewModel {
@Published var count: Int = 0
func increase() {
count += 1
}
}
/// Alternative implementation
class MyOtherViewModel: ViewModel {
@Published var count: Int = 0
func increase() {
count += 2
}
}
/// View with generic parameter that is constrained to
/// the ViewModel protocol
struct MyView<VM>: View where VM: ViewModel {
// @ObservedObject var viewModel: ViewModel // <--- Compiler errors
@ObservedObject var viewModel: VM // <--- Compiler happy :)
var body: some View {
VStack(spacing: 20) {
Text("Count = \(viewModel.count)")
Button(action: {
self.viewModel.increase()
}) {
Text("Increase")
}
}
}
}
struct MyView_Preview: PreviewProvider {
static var previews: some View {
HStack {
MyView(viewModel: MyViewModel())
Spacer()
MyView(viewModel: MyOtherViewModel())
}.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment