(Prenons le cas de l'exécution de 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"]
Vous pouvez faire de même pour vos propres structures.
struct Food: Hashable {
//Méthode de protocole hashable
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