【发布时间】:2021-06-14 17:22:58
【问题描述】:
想象一个卡片板。所有卡片都在我称之为 CardBoard 的视图上。
所有卡片都在一个数组中:
var cards:[Card]
每张卡片都有自己的位置。
这是卡片
struct Card: View {
let id = UUID()
var name:String
var code:String
var filename:String
var position = CGPoint(x: 200, y: 250)
init(name:String, code:String, filename:String) {
self.name = name
self.code = code
self.filename = filename
}
var body: some View {
Image(filename)
.position(position)
}
}
现在我想在屏幕上绘制它们。
var body: some View {
ZStack {
ForEach(cards, id:\.self) {card in
}
}
}
当我尝试这个时,Xcode 会告诉我
Generic struct 'ForEach' requires that 'Card' conform to 'Hashable'
当我将Hashable 添加到Card 时
struct Card: View, Hashable {
1. Stored property type 'CGPoint' does not conform to protocol 'Hashable', preventing synthesized conformance of 'Card' to 'Hashable'
有什么想法吗?
【问题讨论】:
-
您需要向
CGPoint添加一个扩展名以使其可散列。 -
@Alexander 或者直接在
Card上实现Hashable。 -
符合
func hash(into hasher: inout Hasher) { } -
@Sulthan:这可能是更好的解决方案。据我从forums.swift.org/t/retroactive-conformances-vs-swift-in-the-os/… 了解到,将标准库类型的一致性添加到标准库协议追溯性地有一些微妙的问题。