ios - Xcode 不提供添加协议存根
问题描述
我正在尝试使我的 struct Card 符合 Hashable 协议(用于字典),但由于某种原因,Xcode 不会以红色错误对我大喊大叫,例如“Type 'Card' 不符合协议 'Hashable'。我不明白为什么。我希望 Xcode 添加协议存根。
import Foundation
struct Card : Hashable {
var isFaceUp = false
var isMatched = false
var identifier : Int
private static var identifierFactory = 0
private static func getUniqueIdentifier() -> Int {
Card.identifierFactory += 1
return Card.identifierFactory
}
init() {
identifier = Card.getUniqueIdentifier()
}
}
解决方案
它没有显示任何错误,说明您需要添加协议存根以符合它,因为该Hashable
协议是在 struct 上自动合成的Card
。因此,添加Hashable
协议一致性不需要任何额外的代码。
如果由于某种原因您想要覆盖默认实现,您可以通过执行以下操作来实现。
struct Card: Hashable {
//...
func hash(into hasher: inout Hasher) {
hasher.combine(identifier) // combine any hashable you like
}
}
推荐阅读
- python - 如何解决错误消息:“NoneType”对象没有属性“DataFrame”
- sql - SQL Server:在一张表上创建两个外键时出错
- python - Pyinstaller 无法识别 glob.glob 来遍历文件?
- arrays - 如何改进算法来检查数组中是否有一个元素等于数组中任何其他两个元素之间的差?
- sql-server - 仅当存储过程中有值时如何显示结果集
- javascript - 一次又一次地使用相同的查询选择器是否有性能成本?
- mysql - 解决更新同一个表的触发器
- jmeter - 在一定间隔后运行相同的 Jmeter 线程组
- java - 如何在 FTL(Freemarker) 中访问列表的映射
- python - 如何根据开始和结束字符Python获取列表的子集