Note to reader: This was a dumb mistake on my part... I was using @Binding
in my subview when I should have used @ObservedObject
. This lead me to think I needed to cast to Binding<ConcreteModel>
..
I have a published var of type Any?
, I would like to cast it and pass it to a View
expecting Binding<ConcreteModel>
... Is this supported?
Problem with my casting?
// This cast doesn't seem to be working...
if let concreteModel = viewModel.item as? Binding<ConcreteModel> {}
I'm not having success with this:
class ConcreteModel {
public var count = 0
}
class MyViewModel: ObservableObject {
@Published var item: Any?
init() { item = ConcreteModel() }
}
// SwiftUI
struct MyView: View {
@ObservedObject var viewModel = MyViewModel()
var body: some View {
// This cast doesn't seem to be working...
if let concreteModel = viewModel.item as? Binding<ConcreteModel> {
MySecondView(concreteModel: concreteModel)
}
}
}
struct MySecondView: View {
@Binding var concreteModel: ConcreteModel
var body: some View {
Text("\(concreteModel.count)")
}
}
What about using generics? For example ...