您必须做什么才能使设置操作对自定义对象起作用? [英] What must you do to have set operations work on custom objects?

查看:43
本文介绍了您必须做什么才能使设置操作对自定义对象起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个小操场,用自定义对象对 Set 操作进行了一些测试,但它们仍然失败,我不知道为什么.

I made a little playground to do some tests on Set operations with custom objects but they are still failing and I have no idea why.

class User: NSObject {
    let id: String
    init(id: String) {
        self.id = id
        super.init()
    }

    override var hashValue: Int {
        get {
            return id.hashValue
        }
    }

    override var description: String {
        get {
            return id
        }
    }
}


func ==(lhs: User, rhs: User) -> Bool {
    return lhs.hashValue == rhs.hashValue
}

然后,我制作了两组 User 对象:

Then, I made two sets of User objects:

let user1 = User(id: "zach")
let user2 = User(id: "john")
let user3 = User(id: "shane")


let user4 = User(id: "john")
let user5 = User(id: "shane")
let user6 = User(id: "anthony")

let userSet1 : Set<User> = [user1, user2, user3]
let userSet2 : Set<User> = [user4, user5, user6]

但是当我做这样的操作时:

But when I do an operation like so:

let newSet = userSet1.subtract(userSet2)
print(newSet)

newSetuserSet1 相同,并且没有修改任何集合.

newSet is identical to userSet1 and none of the sets are modified.

我必须做什么才能使这些集合操作起作用?

What must I do to get these set operations to work?

id:zach -> 4799450060450308971
id:john -> 4799450060152454338
id:shane -> -4799450060637667915
id:john -> 4799450060152454338
id:shane -> -4799450060637667915
id:anthony -> 4799450059843449897
id:shane -> -4799450060637667915
id:anthony -> 4799450059843449897
id:john -> 4799450060152454338

推荐答案

对于使用什么作为散列值,您无法自行决定.哈希能力的要求是:如果这两个对象相等,则两个对象的哈希值必须相同.

You do not get to make up your own idea of what to use as a hash value. The requirement for hashability is: the hash value of two objects must be the same if those two objects are equal.

您提供了一个哈希值算法,但您没有做任何使您的 User 对象的相等性与其匹配的工作.

You have provided a hash value algorithm but you have done nothing about making equatability of your User objects match it.

这是一个可在集合中散列的 User 对象:

Here is a User object that is hashable in a set:

func ==(lhs:User, rhs:User) -> Bool {
    return lhs.id == rhs.id
}
class User: Hashable, CustomStringConvertible {
    let id: String
    init(id: String) {
        self.id = id
    }
    var hashValue: Int {
        return id.hashValue
    }
}

请注意,我已经消除了使这件事也成为 NSObject 的复杂性.如果您想这样做,事情会有所不同.你需要考虑 NSObject 是如何工作的.

Observe that I have removed the complication of making this thing also an NSObject. Things are a bit different if you want to do that; you'll need to think about how NSObject works.

这篇关于您必须做什么才能使设置操作对自定义对象起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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