如何使用"包含"使用对象的两个数组 [英] How to use "contains" with two arrays of objects

查看:93
本文介绍了如何使用"包含"使用对象的两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类产品

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]()

我用productFirst填充的tableView。

I use productFirst to populate tableView.

我要选择的行添加到productSecond和它的作品:

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])
}

我得到的错误。如何改变呢?当productFirst和productSeconds只是字符串数组它的工作原理确定,但现在我需要的对象。

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

有关错误:首先,它是无法找到一个过载。接受提供的参数删除感叹号是后不能调用包含类型的参数列表(@lvalue [产品,$ T8 )

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)'

推荐答案

有关包含()函数工作产品类应该实现 Equatable 的协议。那是唯一的方式,我们可以检查两个元素是否相等。

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
}

这篇关于如何使用"包含"使用对象的两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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