I'm having some trouble getting my head around conforming existential variables.
Since Animal
here will always conform to Hashable
, I would imagine that any Animal
would also have to conform to Hashable
.
However, the error I'm seeing is causing me to think otherwise. Can someone help explain why this is occurring, and if possible, help me resolve it?
import SwiftUI
import PlaygroundSupport
protocol Animal: Hashable {
var name: String { get }
}
struct Cow: Animal {
let name: String
}
struct Chicken: Animal {
let name: String
}
let anAnimalList: [any Animal] = [Cow(name: "Aaron"), Chicken(name: "Billy"), Cow(name: "Charlie"), Chicken(name: "Delilah")]
struct myView: View {
@State private var anAnimal: (any Animal)?
var body: some View {
VStack {
List(anAnimalList, id: \.self, selection: $anAnimal) { animal in // ERROR: Type 'any Animal' cannot conform to 'Hashable'
Text("Animal")
}
Text("Animal is \(anAnimal?.name ?? "Null")")
}
}
}
PlaygroundPage.current.setLiveView(myView())