简体   繁体   中英

Compare Two Arrays and Remove Duplicates Swift

I have two arrays and I would like to create a new array that compares the two and removes both instances of duplicates.

I have a custom object:

struct SubService: Identifiable, Hashable, Encodable {
   var id: String = UUID().uuidString
   var name: String
   var charge: String
   var price: Double
}

My two arrays:

let array1: [SubService] = [SubService(name: "Men's Haircut", charge: "service", price: 10), SubService(name: "Fade", charge: "service", price: 10)]

let array2: [SubService] = [SubService(name: "Fade", charge: "service", price: 10)]

Here is the result I'm looking for:

let result: [SubService] = [SubService(name: "Men's Haircut", charge: "service", price: 10)]

I have tried the following but it returns the same array as array1 . I'm assuming because of the id ?

let filteredArray = Array(Set(array1).subtracting(array2))

print statements:

ARRAY 1: [SubService(id: "F9EDBBC0-3786-4718-B6BE-C31F26D6E0F0", name: "Fade", charge: "service", price: 10.0), SubService(id: "D91939DD-C339-4A56-B09D-C19ABA56A48B", name: "Men\'s Haircut", charge: "service", price: 10.0)]

ARRAY 2: [SubService(id: "373CE5F9-ECB0-4572-BD27-8BC71F96163B", name: "Fade", charge: "service", price: 10.0)]

FILTERED ARRAY: [SubService(id: "D91939DD-C339-4A56-B09D-C19ABA56A48B", name: "Men\'s Haircut", charge: "service", price: 10.0), SubService(id: "F9EDBBC0-3786-4718-B6BE-C31F26D6E0F0", name: "Fade", charge: "service", price: 10.0)]

Any help is appreciated:)

Reuse your items instead of creating new ones for each array declaration.

let mens = SubService(name: "Men's Haircut", charge: "service", price: 10)
let womens = SubService(name: "Woman's Haircut", charge: "service", price: 10)
let array1 = [mens, womens]
let array2 = [womens]

When you redefine the second item of array1 in let array2 =... , you create a new UUID that makes it different. You can actually see that in your printed values.

SubService has to conform to protocol Equatable

struct SubService: Identifiable, Hashable, Encodable, Equatable  {
   var id: String = UUID().uuidString
   var name: String
   var charge: String
   var price: Double
   static func ==(lhs: SubService, rhs: SubService) -> Bool {
      return lhs.name == rhs.name
   }
}


let arrSet = Set(array2)

let filteredArray = array1.filter{ !arrSet.contains($0) }

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