How to pass a @Binding into a ViewModel.
Let's consider a simple example,
struct TopView: View {
@State var isPresented: Bool
var body: some View {
SubView(isPresented: $isPresented)
}
}
struct SubView: View {
@Binding var isPresented: Bool
}
Then, if we want to a MVVM pattern,
Is it safe to use @Binding in an ObservableObject?
For example, is it safe to write,
struct TopView: View {
@State var isPresented: Bool
var body: some View {
SubView(model: SubViewModel(isPresented: $isPresented))
}
}
struct SubView: View {
@ObservedObject var model: SubViewModel
}
// In "SubViewModel.swift"
import Foundation
import Combine
import SwiftUI
public final class SubViewModel: ObservedObject {
@Binding var isPresented: Bool
public init(isPresented: Binding<Bool>) {
self._isPresented = isPresented
}
}
How would you do it? Similar including how to pass environmentObject into a view model?