What should you do to set up operations on custom objects?

I made a small playground to perform some tests on setting up operations with user objects, but they still do not work, 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 } 

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 this operation:

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

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

What should I do to make these dial operations 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 
+5
source share
1 answer

You cannot make up your own mind on how to use a hash value. Hash requirement: the hash value of two objects must be the same if the two objects are equal.

You provided a hash algorithm, but you did nothing to make your User objects equal.

Here is a custom object that hashable in the 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 } } 

Note that I removed the complexity of making this thing also NSObject. Everything is a little different if you want to do it; you need to think about how NSObject works.

+3
source

Source: https://habr.com/ru/post/1233428/


All Articles