(Consider the case of executing array1 --array2.)
let array1 = ["a", "b", "c", "d", "e"]
let array2 = ["a", "c", "e"]
let unionSet = Set(array1 + array2)
let diffArray = Array(unionSet.subtracting(array2))
print(diffArray)
// ["b", "d"]
You can do the same for your own structures.
struct Food: Hashable {
//Hashable protocol methods
static func == (lhs: Food, rhs: Food) -> Bool {
return (lhs.name == rhs.name) && (lhs.price == rhs.price)
}
let name: String
let price: Int
}
let food1 = Food(name: "ramen", price: 800)
let food2 = Food(name: "Udon", price: 700)
let food3 = Food(name: "Soba", price: 600)
let myFavoriteFood = [food1, food2, food3]
let yourFavoriteFood = [food1]
let unionSet = Set(myFavoriteFood + yourFavoriteFood)
let diffArray = Array(unionSet.subtracting(yourFavoriteFood))
print(diffArray[0], diffArray[1])
// Food(name: "Udon", price: 700) Food(name: "Soba", price: 600)
Recommended Posts