我是一名Swift新手,我正试图掌握以下数据结构。我有categories
结构的数组(category
)。每个category
结构包含一个business
结构数组,存储为属性items
上的值。我不知道如何表示这种事情,但希望这个伪代码能让它更清晰一些:
categories: [category]
- category: Struct
.categoryId: Int
.items: [business]
- business: Struct
.busId: Int
- business: Struct
.busId: Int
- category: Struct
.categoryId: Int
.items: [business]
- business: Struct
.busId: Int
- business: Struct
.busId: Int
给定busId
我正在尝试返回匹配的business
结构和包含它的categoryId
。我已经尝试过使用FlatMap和Map,但是我会绕圈试图解开并过滤这个数据结构。
关于采取措施的任何指示/建议都会很棒。
答案 0 :(得分:2)
struct Business {
let busID: Int
}
struct Category {
let categoryID: Int
let business: [Business]
}
let categories = [
Category(categoryID: 0, business: [Business(busID:0)]),
Category(categoryID: 1, business: [Business(busID:1), Business(busID:2)])
]
func search(businessID: Int, categories: [Category]) -> (categoryID: Int, business:Business)? {
let res = categories.reduce([Int:Business]()) { (res, category) -> [Int:Business] in
guard res.isEmpty else { return res }
var res = res
if let business = (category.business.filter { $0.busID == businessID }).first {
res[category.categoryID] = business
}
return res
}
guard let categoryID = res.keys.first, business = res[categoryID] else { return nil }
return (categoryID, business)
}
这是一个较短的版本,不使用reduce
func search(businessID: Int, categories: [Category]) -> (categoryID: Int, business:Business)? {
guard let
category = (categories.filter { $0.business.contains { $0.busID == businessID } } ).first,
business = (category.business.filter { $0.busID == businessID } ).first
else { return nil }
return (category.categoryID, business)
}
答案 1 :(得分:1)
这是怎么回事?
categories.filter{category in //filter the categories as the final result
category.items //get the Businesses in the category
.map{$0.busId} //get the busIds of the Businesses
.contains(desiredBusinessID) //keep iff the desired busId is present
}