Conforming to the Hashable Protocol

To use your own custom type in a set or as the key type of a dictionary, add Hashable conformance to your type. The Hashable protocol inherits from the Equatable protocol, so you must also satisfy that protocol’s requirements.

The compiler automatically synthesizes your custom type’s Hashable and requirements when you declare Hashable conformance in the type’s original declaration and your type meets these criteria:

  • For a struct, all its stored properties must conform to Hashable.
  • For an enum, all its associated values must conform to Hashable. (An enum without associated values has Hashable conformance even without the declaration.)

To customize your type’s Hashable conformance, to adopt Hashable in a type that doesn’t meet the criteria listed above, or to extend an existing type to conform to Hashable, implement the hash(into:) method in your custom type.

In your hash(into:) implementation, call combine(_:) on the provided Hasher instance with the essential components of your type. To ensure that your type meets the semantic requirements of the Hashable and Equatable protocols, it’s a good idea to also customize your type’s Equatable conformance to match.

As an example, consider a GridPoint type that describes a location in a grid of buttons. Here’s the initial declaration of the GridPoint type:

/// A point in an x-y coordinate system.

struct GridPoint {

var x: Int

var y: Int

}

You’d like to create a set of the grid points where a user has already tapped. Because the GridPoint type is not hashable yet, it can’t be used in a set. To add Hashable conformance, provide an == operator function and implement the hash(into:) method.

extension GridPoint: Hashable {

static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {

return lhs.x == rhs.x && lhs.y == rhs.y

}

func hash(into hasher: inout Hasher) {

hasher.combine(x)

hasher.combine(y)

}

}

The hash(into:) method in this example feeds the grid point’s x and y properties into the provided hasher. These properties are the same ones used to test for equality in the == operator function.

Now that GridPoint conforms to the Hashable protocol, you can create a set of previously tapped grid points.

var tappedPoints: Set = [GridPoint(x: 2, y: 3), GridPoint(x: 4, y: 1)]

let nextTap = GridPoint(x: 0, y: 1)

if tappedPoints.contains(nextTap) {

print("Already tapped at (\(nextTap.x), \(nextTap.y)).")

} else {

tappedPoints.insert(nextTap)

print("New tap detected at (\(nextTap.x), \(nextTap.y)).")

}

// Prints "New tap detected at (0, 1).")

 https://developer.apple.com/documentation/swift/hashable

swift的Hashable的更多相关文章

  1. swifter技巧(100)

    一.swift新元素 Tip1:柯里化 将方法进行柯里化,把接受多个参数的方法变换成接受第一个参数的方法,并且返回接受余下的参数,返回结果的新方法. func addTwoNumbers(a: Int ...

  2. swift Hashable Equatable

    /// You can use any type that conforms to the `Hashable` protocol in a set or /// as a dictionary ke ...

  3. Swift mutating Equatable Hashable 待研究

    Swift mutating Equatable Hashable 待研究

  4. Swift自定义Class实现Hashable

    假如有个Bit类,其中含有CGPoint类型的point属性,Class定义如下 class Bit { var point : CGPoint init(point : CGPoint) { sel ...

  5. 窥探Swift之数组与字典

    说到数组和字典,只要是编过程的小伙伴并不陌生.在Swift中的数组与字典也有着一些让人眼前一亮的特性,今天的博客就来窥探一下Swift中的Array和Dictionary.还是沿袭之前的风格,在介绍S ...

  6. 浅谈Swift集合类型

    Swift 的集合表现形式由数组和字典组成.它可以完美的存储任何呢想存储的东西. 数组是一个同类型的序列化列表集合,它用来存储相同类型的不同值.字典也是一个数组,但它的存值方式类似于Map,通过一对一 ...

  7. iOS - Swift 基本语法

    前言 Swift 全面支持 Unicode 符号. Swift 中的定义和实现是在同一个单元中的,通常一个 Swift 源代码单文件是以 ".Swift" 结尾的. Swift 不 ...

  8. Swift Explore - 关于 Swift 中的 isEqual 的一点探索

    在我们进行 App 开发的时候,经常会用到的一个操作就是判断两个对象是否相等.比如两个字符串是否相等.而所谓的 相等 有着两层含义.一个是值相等,还有一个是引用相等.如果熟悉 Objective-C ...

  9. swift:入门知识之泛型

    在尖括号里写一个名字来创建一个泛型函数或者类型 例如<T>.<Type> 可以创建泛型类.枚举和结构体 在类型后使用where来指定一个需求列表.例如,要限定实现一个协议的类型 ...

随机推荐

  1. IE浏览器TAB清空设置

    1.Regedit 2.HKEY_USERS——搜索NewTabPage 3.清空除了Default之外的所有东西 4.也可以添加NumRows——TAB的行数 可以参考:http://tieba.b ...

  2. 【JavaScript 从零开始】 语言核心部分----可选的分号

    Node.js很是火爆,前段待遇好的飞起.... 于是我决定.... 重头开始学习JavaScript有些比较特别的,或者之前我们注意到,再或者容易出错东西我会记录下来. 可选的分号 和其他许多编程语 ...

  3. div中让文字垂直居中

    在div中如何让文字垂直居中? 作者在刚接触web前端开发时就遇到了这个问题,一直没有记录下来,今天正好有空,便记录下来. 为了方便展示,我把style先直接写在了div里. 效果如下图所示: 图1. ...

  4. JS中的事件冒泡——总结

    一. 有话要说 事件冒泡这个话题已经被园子里的朋友说透了,已经没什么要讲的了,但是由于呢我这边有个小问题刚好跟这个事件冒泡有关,就突然性想写个总结:一方面是给自己增加印象,另一方面给园子的新手们,提供 ...

  5. java获得Tomcat服务器的根目录下的内容

    File f2=new File(System.getProperty("catalina.home")+ File.separator+"webapps"+F ...

  6. java设计模式-----17、中介者模式

    概念: Mediator模式也叫中介者模式,是由GoF提出的23种软件设计模式的一种.Mediator模式是行为模式之一,在Mediator模式中,类之间的交互行为被统一放在Mediator的对象中, ...

  7. [清华集训]Rmq Problem / mex

    题目链接 我们离线处理这些询问 在右端点所在的位置用vector来push_back询问 维护每个数值最后出现的位置p[x] 从左往右扫,边走边回答询问 对于每个询问我们回答第一个p[x]<l的 ...

  8. CentOS7.4 + Hadoop2.9安装配置管理(分布式)

    1.  规划 1.1.  机器列表 NameNode SecondaryNameNode DataNodes 192.168.1.121 192.168.1.122 192.168.1.101 192 ...

  9. fuzz系列之afl

    afl 实战 前言 像 libFuzzer, afl 这类 fuzz 对于 从文件 或者 标准输入 获取输入的程序都能进行很好的 fuzz, 但是对于基于网络的程序来说就不是那么方便了. 这篇文章介绍 ...

  10. 使用Spring操作Redis的key-value数据

    前言 最近工作一直忙的不可开交,小Alan已经很久没有和大家分享知识了,在深圳待了两年多,依然感觉自己还是个小菜鸟,工作中还是会遇到很多自己在短期内无法搞定的事情,每当这个时候总是会感觉到很沮丧,就会 ...