简体   繁体   中英

How to use “contains” with two arrays of objects

I have class Products

class Products {

    var name:String = ""
    var number:Int = 0

    init(name: String, number: Int) {
        self.name = name
        self.number = number
    }
}

Then in view controller

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

I use productFirst to populate tableView.

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

productSecond.append(productFirst[indexPath.row])

But I don't want to duplicate items in array, so I did

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

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

About error: First it is "could not find an overload for "!" that accepts the supplied arguments. After deleting exclamation mark it is "cannot invoke contains with an argument list of type '(@lvalue[Products,$T8)'

For contains() function to work the Products class should implement Equatable protocol. That's the way only we can check whether 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM