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. 使用 ahk 让普通键盘变为Dvorak键盘

    本文告诉大家,如何使用软件做出Dvorak键盘. 在开始说如何做之前,需要告诉大家,什么是Dvorak键盘. Dvorak Simplified Keyboard /ˈdvɔːræk, dəˈvɔː- ...

  2. Hibernate中一级缓存概念以及flush与clear的区别

    Hibernate采用缓存机制提高数据查询效率.缓存分为一级缓存和二级缓存,一级缓存在Session中存在,二级缓存需要手动配置. 在一级缓存中,如果数据保存到数据库中后,而session又没有关闭的 ...

  3. lombok入门

    pom.xml加入依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lo ...

  4. Java Swing实战(五)表格组件JTable(1)

    dbPanel面板的配置告一段落. 接下来配置taskPanel 面板. /** * @author: lishuai * @date: 2018/11/26 13:51 */ public clas ...

  5. Java 如何重写对象的 equals 方法和 hashCode 方法

    前言:Java 对象如果要比较是否相等,则需要重写 equals 方法,同时重写 hashCode 方法,而且 hashCode 方法里面使用质数 31.接下来看看各种为什么. 一.需求: 对比两个对 ...

  6. K:图的存储结构

      常用的图的存储结构主要有两种,一种是采用数组链表(邻接表)的方式,一种是采用邻接矩阵的方式.当然,图也可以采用十字链表或者边集数组的方式来进行表示,但由于不常用,为此,本博文不对其进行介绍. 邻接 ...

  7. github|webstorm

    分享本地项目到github 从github上迁出项目到本地

  8. 浏览器从输入到输出的过程与原理三之DNS

    1. DNS 在互联网上的每一个计算机都拥有一个唯一的地址,称作“IP地址”(即互联网协议地址).由于IP地址(为一串数字)不方便记忆,DNS允许用户使用一串常见的字母(即“域名”)取代.比如,您只需 ...

  9. android studio使用openssl

    前言 逆向的基础是开发, 逆向分析时很多时候会使用一些公开的加密函数来对数据进行加密,通过使用 openssl 熟悉下. 正文 首先得先编译出来 openssl,然后把它们复制到你的工程目录下. in ...

  10. 【CVE-2018-11116】openwrt rpcd 配置文件错误导致访问控制失效

    User can access to ubus over HTTP. This way depend on rpcd service. When misconfigure the rpcd's ACL ...