簡體   English   中英

Swift 5.7 - 使存在的“任何”協議符合 Hashable

[英]Swift 5.7 - Make existential 'any' protocol conform to Hashable

我在理解一致的存在變量時遇到了一些麻煩。

由於這里的Animal將始終符合Hashable ,我想any Animal必須符合Hashable

但是,我看到的錯誤讓我不這么認為。 有人可以幫助解釋為什么會發生這種情況,如果可能的話,幫我解決它?

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 的回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM