如何从swift中的对象数组中消除重复的对象

时间:2017-05-17 11:44:11

标签: arrays swift

我有两个来自Web服务的数组,我需要找出Array2是否与Array1具有相同的对象。 所以,为此我使用下面的代码:

{{1}}

但它在上面的行“Array(Set(arr3))”上显示错误 错误是: - 为Set

添加值

2 个答案:

答案 0 :(得分:0)

试试这个:

var arr1 = ["A","B","C"]
var arr2 = ["A","B","C"]

if Set(arr1).symmetricDifference(arr2).isEmpty {
    print("The Arrays Match")
}

答案 1 :(得分:0)

概述:

  • 为了使集合存储自定义类/结构,自定义类/结构需要符合Hashable protocol和间接Equatable protocol
  • 以下是使用struct的示例,您也可以使用类。

代码:

struct CustomObject : Hashable{

    var something : Int //It is just an example, this could be any type, but some how you should find a way to compute the hash value.

    //MARK: Hashable
    var hashValue: Int {

        return something
    }
}

//MARK: CustomObject - Equatable
func ==(lhs: CustomObject, rhs: CustomObject) -> Bool {

    return lhs.something == rhs.something
}
相关问题