I didn't find any posts/ways to load/manage different objects in the same view in SwiftUI. The goal is to not multiply same code.
Supposing I have 3 structs/instances Country, Region, Subregion with same properties: id, name, image.
struct Country: Identifiable, Codable, Hashable {
var id: Int64?
var name: String
var image: String
}
struct Region: Identifiable, Codable, Hashable {
var id: Int64?
var name: String
var image: String
}
struct Subregion: Identifiable, Codable, Hashable {
var id: Int64?
var name: String
var image: String
}
In a a parent view, I want to send instances to the child view as a binding:
ButtonNavigationLink(descriptorItem: descriptorItem, selectedItem: $finderViewModel.referenceCountry)
ButtonNavigationLink(descriptorItem: descriptorItem, selectedItem: $finderViewModel.referenceRegion)
ButtonNavigationLink(descriptorItem: descriptorItem, selectedItem: $finderViewModel.referenceSubregion)
Note: I don't want to send the same properties to the child view, this is easy. I want to send the struct itself (model). I need it in the child view.
So now, I want to receive the model/struct in the child view. I have done multiple try such:
- using generics:
@Binding var selectedItem: GenericType?
=> the problem is I don't know how to read the properties from the generic (cast ?) - trying AnyHashable:
@Binding var selectedItem: AnyHashable?
=> the compiler is lost between the type sent (country) and AnyHashable type
Well, I am lost. :-)
My subview that receive the "generic" binding looks like that:
// struct ButtonNavigationLink <T>: View where T: Hashable { // => if generic
struct ButtonNavigationLink: View {
var descriptorItem: DescriptorItem
@Binding var selectedItem: AnyHashable?
// Generic type
//@Binding var selectedItem: GenericType?
//typealias GenericType = T
}
So what's the best solution to not multiply views for each object ? The child view goal is to select the item in the @Binding, not only to display data... that's why I need to full object and not only the properties as @Binding.
Button (action: {
selectedItem = descriptorItem
})
Thanks in advance for any help/suggestion.