gpt4 book ai didi

arrays - 如何根据名称数组过滤数组?

转载 作者:搜寻专家 更新时间:2023-11-01 07:12:44 25 4
gpt4 key购买 nike

我有 2 个数组。在第一个数组中,我有一个要从第二个数组中删除的名单。

第一个数组只是字符串数组:

var arrayNames = ["apple", "apricot", "cucumber"]

第二个数组是自定义结构的数组:

struct fruitsData {
var name: String?
}

var secondArray = [fruitsData(name: "apple"),fruitsData(name: "apricot"), fruitsData(name: "mango"), fruitsData(name: "grapes"), fruitsData(name: "tomato"), fruitsData(name: "lichi"), fruitsData(name: "cucumber"), fruitsData(name: "brinjal")]

那么我怎样才能得到只包含这些数据的数组:

var finalData = [fruitsData(name: "mango"), fruitsData(name: "grapes"), fruitsData(name: "tomato"), fruitsData(name: "lichi"), fruitsData(name: "brinjal")]

哪个不包含 arrayNames 中的任何名称?

最佳答案

有几种方法可以做到这一点:

  • 最好的方法是使用 filter 方法:

    var arrayNames = ["apple", "apricot", "cucumber"]
    var secondArray = [fruitsData(name: "apple"),fruitsData(name: "apricot"), fruitsData(name: "mango"), fruitsData(name: "grapes"), fruitsData(name: "tomato"), fruitsData(name: "lichi"), fruitsData(name: "cucumber"), fruitsData(name: "brinjal")]

    secondArray = secondArray.filter({$0.name != nil && !arrayNames.contains($0.name!)})
  • 或者,如果您想为了可读性而牺牲效率,您可以将 for-in 循环与辅助数组一起使用:

    var arrayNames = ["apple", "apricot", "cucumber"]
    var secondArray = [fruitsData(name: "apple"),fruitsData(name: "apricot"), fruitsData(name: "mango"), fruitsData(name: "grapes"), fruitsData(name: "tomato"), fruitsData(name: "lichi"), fruitsData(name: "cucumber"), fruitsData(name: "brinjal")]
    var helperArray = [fruitsData]()

    for fruit in secondArray {

    if fruit.name != nil && !arrayNames.contains(fruit.name!){
    helperArray.append(fruit)
    }

    }

    secondArray = helperArray

上面的代码将从 secondArray 中删除其名称包含在 arrayNames 中的每个元素。您应该熟悉 Map, Filter and Reduce .

关于arrays - 如何根据名称数组过滤数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com