gpt4 book ai didi

arrays - 用对象过滤嵌套数组

转载 作者:可可西里 更新时间:2023-11-01 00:39:01 36 4
gpt4 key购买 nike

我有一组类别。每个 Category 实例都有 offers 属性。

class Category {
var offers : [Offer]?
var title : String?
var id : Int?
}

class Offer {
var type : String?
}

//global variable
var categories = [ categ1, categ2, ...]

如何按 offer.type 筛选类别?

我已经试过了:

return categories.map { (category) -> Category in
let offers = category.offers?.filter { $0.type == myType }
category.offers = offers
return category
}

它有效,但在第二次调用函数后数组变为空。可能是因为报价被重写了?

然后我尝试了这个(产生了同样的错误结果):

var resultCategories = [Category]()

for category in categories {
guard let offers = category.offers else { continue }

var newOffers = [Offer]()

for offer in offers {
if offer.type == myType {
newOffers.append(offer)
}
}

category.offers = newOffers
resultCategories.append(category)
}

return resultCategories

最佳答案

您应该简单地过滤所有没有符合您的类型的商品的类别。您可以通过以下方式实现:

  1. 筛选所有类别并
  2. filter 中检查当前商品是否包含 myType

代码:

let filtered = categories.filter { category in
category.offers?.contains(where: { $0.type == myType }) ?? false
}

请注意,category.offers?.[...] 是可选值,所以 ?? false 如果左侧部分为 nil,则返回 false 作为结果。


更新。

But I expected that categories will have only offers with type = "A". Maybe I did not described the question accurately.

您可以通过创建一个新的 Category 来实现。

let filtered = categories.compactMap { category -> Category? in
guard let offers = category.offers?.filter({ $0.type == "A" }) else { return nil }
let other = Category()
other.offers = offers
return other
}

另请注意,我正在使用 compactMap。它允许我过滤出空的或 nil offers 的类别。

关于arrays - 用对象过滤嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51360682/

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