swift 两个不同数组中的Match属性

6bc51xsx  于 2023-03-22  发布在  Swift
关注(0)|答案(2)|浏览(115)

我试图在两个不同的数组中匹配属性flavour
阵列一:

var myIcecreams = [
    Icecream(color: "yellow", flavour: "banana"),
    Icecream(color: "green", flavour: "mint"),
    Icecream(color: "white", flavour: "banana"),
    Icecream(color: "brown", flavour: "chocolate")
]

阵列二:

var shopIcecreams = [
    Icecream(color: "red", flavour: "strawberry"),
    Icecream(color: "purple", flavour: "blueberry"),
    Icecream(color: "green", flavour: "pistachio"),
    Icecream(color: "white", flavour: "chocolate")
]

如何创建一个新数组,包含shopIcecreams中的所有元素,除了属性flavour相互匹配的元素?冰淇淋中有一个匹配的chocolate作为风味,应该在新数组中删除。
我试过了,没有运气:

let filteredIcecreams = shopIcecreams.filter { newIcecream in
    myIcecreams.contains { myIcecream in
        newIcecream.flavour != myIcecream.flavour
    }
}

我做错了什么?我毫无头绪。
冰淇淋结构:

struct Icecream: Encodable, Decodable {
    var color: String
    var flavour: String
}
k10s72fa

k10s72fa1#

这是我认为你想要的:

// All of the different flavours in myIcecreams as a Set to remove
// duplicates and increase performance of looking up flavours
// ["banana", "mint", "chocolate"]
let myFlavours = Set(myIcecreams.map { $0.flavour })

// All entries from `shopIcecreams` with a flavour not in `myFlavours`
let filteredIcecreams = shopIcecreams.filter { shopIcecream in
    !myFlavours.contains(shopIcecream.flavour)
}
wf82jlnq

wf82jlnq2#

struct Icecream: Encodable, Decodable {
    var color: String
    var flavour: String
}

var myIcecreams = [
    Icecream(color: "yellow", flavour: "banana"),
    Icecream(color: "green", flavour: "mint"),
    Icecream(color: "white", flavour: "banana"),
    Icecream(color: "brown", flavour: "chocolate")
]

var shopIcecreams = [
    Icecream(color: "red", flavour: "strawberry"),
    Icecream(color: "purple", flavour: "blueberry"),
    Icecream(color: "green", flavour: "pistachio"),
    Icecream(color: "white", flavour: "chocolate")
]

var newArray: [Icecream] = []

for i in shopIcecreams {
    var match = false
    for j in myIcecreams {
        if i.flavour == j.flavour {
            match = true
            break
        }
        else {
            match = false
        }
    }
    if match == false {
        newArray.append(i)
    }
}

// Printing new array
for i in newArray {
    print(i)
}

Click Here to see the output

输出:

冰淇淋(颜色:“红色”,风味:“草莓”)冰淇淋(颜色:“紫”,味:“蓝莓”)冰淇淋(颜色:“绿色”,风味:“开心果”)

相关问题