swift – 符合Hashable协议?

前端之家收集整理的这篇文章主要介绍了swift – 符合Hashable协议?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用键创建一个字典作为我创建的结构,并将值作为Ints数组.但是,我一直收到错误:类型’dateStruct’不符合协议’Hashable’.我很确定我已经实现了必要的方法但由于某种原因它仍然不起作用.这是我的结构与实现的协议:
  1. struct dateStruct {
  2. var year: Int
  3. var month: Int
  4. var day: Int
  5.  
  6. var hashValue: Int {
  7. return (year+month+day).hashValue
  8. }
  9.  
  10. static func == (lhs: dateStruct,rhs: dateStruct) -> Bool {
  11. return lhs.hashValue == rhs.hashValue
  12. }
  13.  
  14. static func < (lhs: dateStruct,rhs: dateStruct) -> Bool {
  15. if (lhs.year < rhs.year) {
  16. return true
  17. } else if (lhs.year > rhs.year) {
  18. return false
  19. } else {
  20. if (lhs.month < rhs.month) {
  21. return true
  22. } else if (lhs.month > rhs.month) {
  23. return false
  24. } else {
  25. if (lhs.day < rhs.day) {
  26. return true
  27. } else {
  28. return false
  29. }
  30. }
  31. }
  32. }
  33. }

任何人都可以向我解释为什么我仍然会收到错误

你错过了声明:
  1. struct dateStruct: Hashable {

BTW – 结构和类名称应以大写字母开头.

你的==函数错误的.您应该比较这三个属性.

  1. static func == (lhs: dateStruct,rhs: dateStruct) -> Bool {
  2. return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day
  3. }

两个不同的值可能具有相同的哈希值.

猜你在找的Swift相关文章