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. mysql sql语句大全(MySQL语句 整理一)

    1.说明:创建数据库 CREATE DATABASE database-name 2.说明:删除数据库 drop database dbname 3.说明:备份sql server --- 创建 备份 ...

  2. 【原】Maven解决Jar包冲突

    一.起源 引入二方jar maven 包后出现 NoSuchMethodError org.apache.commons.lang3.StringUtils.isNoneEmpty . 第一感觉就是j ...

  3. spring boot在intellij idea下整合mybatis可能遇到的问题

    org.apache.ibatis.builder.BuilderException: Wrong namespace. Expected 'com.sc.starry_sky.dao.UserMap ...

  4. Form表单中Post与Get方法的区别

    Form提供了两种数据传输的方式:get和post.虽然它们都是数据的提交方式,但是在实际传输时确有很大的不同,并且可能会对数据产生严重的影响. Form中的get和post方法,在数据传输过程中分别 ...

  5. chrome跨域访问

    这里设计到跨域访问的问题,如果非要在本地来访问,可以这是chrome的参数. 1.打开chrome快捷方式->属性 2.末尾添加: --args --disable-web-security 3 ...

  6. SpringMVC接受请求参数、

    1. 接收请求参数 1.1. [不推荐]通过HttpServletRequest 在处理请求的方法中,添加HttpServletRequest对象作为参数,在方法体中,直接调用参数对象的getPara ...

  7. 企业实施ERP的先后步骤,你真的了解吗?

    信息化是我国加快实现工业化和现代化的必然选择.坚持以信息化带动工业化,以工业化促进信息化,在国民经济和社会领域广泛采用信息技术.国民经济信息化中企业的信息化工作是基础, ERP管理系统是IT技术和先进 ...

  8. 关于Datastage资料库的一点小发现

    这里的资料库,指的是Datastage Metadata层,在Datastage7.5以后,需要在安装Datastage时安装一个数据库用于存放用户数据. 昨天领导要求安装Datastage集群/高可 ...

  9. solidity 语法学习

    基于 cryptozombies.io ZombieFactory pragma solidity ^0.4.19; contract ZombieFactory { // 事件, web3.js 可 ...

  10. java 内存分析之方法返回值及匿名对象一

    package Demo; public class Point { private double x, y, z; public Point(double _x, double _y, double ...