简体   繁体   中英

Swift 5.7 - Make existential 'any' protocol conform to Hashable

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())

我发现这个答案解释了发生这种情况的原因以及如何解决它: Scott Thompson 的回答

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM