使协议符合Swift中的Hashable
我正在尝试循环通过具有不同类型的练习的数组。为此,我声明了一个可以通过数组保存的协议。我想将Hashable协议添加到我的Anyerecise协议中。但是我会收到以下错误:协议'any ercercise'作为一种类型不能符合“ hashable”
我尝试了以下内容:
protocol AnyExercise {
var id: UUID {get}
var name: String {get}
var description: String {get}
func hash(into hasher: inout Hasher)
}
typealias Exercise = AnyExercise & Identifiable & Hashable
extension Break: Exercise {}
extension Pause: Exercise {}
extension Run: Exercise {}
extension Sprint: Exercise {}
示例结构实现:
struct Sprint {
var id = UUID()
var name: String
var description: String
init() {
self.name = "Sprint"
self.description = "Sprint"
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
hasher.combine(description)
}
}
任何想法如何解决这个问题?还是在数组中保持多种不同类型?谢谢。
I am trying to loop through an array which holds different types of exercises. In order to do so, I declared a protocol AnyExercise which can be hold by an array. I would like to add the Hashable protocol to my AnyExercise protocol. But I am getting the following error: Protocol 'AnyExercise' as a type cannot conform to 'Hashable'
I tried the following:
protocol AnyExercise {
var id: UUID {get}
var name: String {get}
var description: String {get}
func hash(into hasher: inout Hasher)
}
typealias Exercise = AnyExercise & Identifiable & Hashable
extension Break: Exercise {}
extension Pause: Exercise {}
extension Run: Exercise {}
extension Sprint: Exercise {}
Example struct implementation:
struct Sprint {
var id = UUID()
var name: String
var description: String
init() {
self.name = "Sprint"
self.description = "Sprint"
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
hasher.combine(description)
}
}
Any ideas how to solve this? Or hold multiple different types in an array? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管以下内容不会使协议
any codecise
hashable
,但它确实让您拥有具有不同类型的数组,符合您的
any cockise
协议,并且在Swiftui中可用,使用
id:\ .id
,如示例代码:although the following does not make the protocol
AnyExercise
Hashable
, it does let you havean array with different types conforming to your
AnyExercise
protocol and usable in SwiftUI,using the
id: \.id
, as in the example code: