在Swift中比较两个对象数组

时间:2019-04-30 01:10:54

标签: arrays swift difference

我有两个大小不同的对象数组。 第一个包含旧数据,第二个包含来自服务器的更新数据(包括旧数据和新数据),可以混合数据。我想弄清楚这些数组之间的区别。

我的课

class Station {
  var dateOfIssue: Date
  var region: String
  var locality: String
  var bsName: String
  var freqIn: String
  var freqOut: String
  var networkType: String
  var provider: String
  var bsUsableName: String
  ...
}

我要比较的数组(示例)

var a = [Station]()
var b = [Station]()
for _ in 0...5 {      
  a.append(Station(someRandomStationValue...)
}
b = a
for _ in 0...7{
  b.append(Station(someRandomStationValue...)  //array "b" will contain all that array "a" contains and some new values
}

如何比较这些数组,比较它们之间的所有字段并获得具有差异的新数组(例如在Java中:b.removeAll(a))?

3 个答案:

答案 0 :(得分:1)

您可以利用提供内置Set.subtract()方法的.subtracting()来删除两个 Set

中的通用条目。
struct Station: Hashable,CustomStringConvertible {
    var id: Int
    var region: String
    var locality: String
    var bsName: String

    // Just to provide a pretty print statement
    var description: String {
        return "ID: \(id) | region: \(region) | locality: \(locality) | bsName: \(bsName)"
    }
}

var stations1 = Set<Station>()
var stations2 = Set<Station>()

for currentNumber in 0...3 {
    stations1.insert(Station(id: currentNumber, region: "abc", locality: "abc", bsName: "abc"))
}

for currentNumber in 0...5 {
    stations2.insert(Station(id: currentNumber, region: "abc", locality: "abc", bsName: "abc"))
}

// Caluculating the difference here
print(stations2.subtracting(stations1))

答案 1 :(得分:0)

如koropok的评论中所述,您可以使用subtract方法:

// Added to make original code functional 
// Station must conform to Hashable protocol in order to be stored in the Set
struct Station: Hashable {
    let id: Int
}

var a = [Station]()
for i in 0...5 {
    a.append(Station(id:i))
}

var b = [Station]()
for i in 0...7{
    //array "b" will contain all that array "a" contains and some new values
    b.append(Station(id:i))  
}

var c = Set(b)

// c will contain 6 and 7
c.subtract(a)

答案 2 :(得分:0)

如@koropok所指出的那样,一个好的解决方案是使用Set。第一步是使您的类型符合Hashable。对于类,您必须实现==hash(into:)函数,但是如果使用struct,则除了声明一致性以外,无需执行其他任何操作。所以:

struct Station: Hashable {
  var dateOfIssue: Date
  var region: String
  ...
}

现在,您应该可以将Station添加到Set中了。因此:

var a = Set<Station>()
for _ in 0...5 {
  a.insert(Station(...))
}
var b = Set<Station>()
a.forEach { b.insert($0) }
for _ in 0...7 {
  b.insert(Station(...))
}

let c = b.subtracting(a)

Set还提供了一个方便的初始化器,可用于将Station数组变成集合:

let s = Set(arrayLiteral: [your, station, objects])