How to use "contains" with two arrays of objects

I have a class Products

class Products { var name:String = "" var number:Int = 0 init(name: String, number: Int) { self.name = name self.number = number } } 

Then in the field of view of the controller

 var productFirst:[Products] = [Products(name: "First", number: 1)] var productSecond:[Products] = [Products]() 

I use productFirst to populate a tableView.

I want to add the selected row to productSecond and it works:

 productSecond.append(productFirst[indexPath.row]) 

But I do not want to duplicate the elements in the array, so I did

 if !contains(productSecond, productFirst[indexPath.row]) { productSecond.append(productFirst[indexPath.row]) } 

I get an error. How to change it? When productFirst and productSeconds are just arrays of strings, it works fine, but now I need objects.

On the error: firstly, "could not find an overload for"! "which accepts the provided arguments. After removing the exclamation mark, it" cannot call contains a list of arguments of the type "(@lvalue [Products, $ T8) '

0
source share
1 answer

For the contains() function, the Equatable protocol must be implemented for the Products class to work. That we can check only two elements are equal.

 class Products : Equatable { var name:String = "" var number:Int = 0 init(name: String, number: Int) { self.name = name self.number = number } } func ==(lhs: Products, rhs: Products) -> Bool { return lhs.name == rhs.name && lhs.number == rhs.number } 
+3
source

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


All Articles