I am trying to use several objects that conform to a custom protocol in a TabView
with SwiftUI. The problem is, when I write the below code, I get this error on the TabView
:
Type 'any Target' cannot conform to 'Hashable'
How can I fix this issue? My code is below:
protocol Target {
var id: Int { get }
var name: String { get }
}
struct Target1: Target {
var id: Int = 1
var name: String = "Target1"
}
struct Target2: Target {
var id: Int = 2
var name: String = "Target2"
}
struct Target3: Target {
var id: Int = 3
var name: String = "Target3"
}
struct ContentView: View {
let targets: [any Target] = [Target1(), Target2(), Target3()]
@State private var selectedTarget: any Target = Target1()
var body: some View {
NavigationStack {
TabView(selection: $selectedTarget) { // This is where the error occurs.
ForEach(targets, id: .id) { target in
Text(target.name)
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
}
}
}