嵌套的结构数组中的Swift匹配元素

时间:2016-06-14 19:08:14

标签: ios swift

我是一名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,但是我会绕圈试图解开并过滤这个数据结构。

关于采取措施的任何指示/建议都会很棒。

2 个答案:

答案 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)])
]

我们可以提取categoryID和具有给定Int

的Business
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)
}

实施例

enter image description here

更新

这是一个较短的版本,不使用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
}