Swift,如何基于对象引用实现哈希协议? [英] Swift, how to implement Hashable protocol based on object reference?

查看:53
本文介绍了Swift,如何基于对象引用实现哈希协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java之后,我已经开始学习敏捷.在Java中,我可以将任何对象用作HashSet的键,因为它基于对象标识符具有默认的hashCodeequals.如何在Swift中实现相同的行为?

I've started to learn swift after Java. In Java I can use any object as a key for HashSet, cause it has default hashCode and equals based on object identifier. How to achieve the same behaviour in Swift?

推荐答案

如果您使用的是类而不是结构,则可以使用

If you are working with classes and not structs, you can use the ObjectIdentifier struct. Note that you also have to define == for your class in order to conform to Equatable (Hashable requires it). It would look something like this:

class MyClass: Hashable { }

func ==(lhs: MyClass, rhs: MyClass) -> Bool {
    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}

class MyClass: Hashable {
    var hashValue: Int {
        return ObjectIdentifier(self).hashValue
    }
}

这篇关于Swift,如何基于对象引用实现哈希协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆