簡體   English   中英

如何在字典數組中的內部數組上應用過濾器?

[英]how to apply filter on inside array in array of dictionary?

我有一種情況,例如我有字典數組,其中每個鍵都有特定對象的數組。 像這樣。

    // example setup
    struct FruitsData {
        var name: String?
        var id: String?
    }

tableViewSource = [String : [FruitsData]]

所以我必須在這個內部數組上應用過濾器。 但是我無法更新最終數組中的值。 我已經寫了這段代碼。

tableViewSource = tableViewSource.filter { ( dictData: (key: String, value: [FruitsData])) -> Bool in
    var arrFruitsData = dictData.value
    arrFruitsData = arrFruitsData.filter{ ( $0.id != nil) }

    if arrFruitsData.count == 0 {
        self.tableViewHeaders = self.tableViewHeaders.filter { $0 != dictData.key }
    }
    return true

    }

就像我已經刪除了ID已刪除的數組中的那些值。

例如,如果我在數組中有這些值。

var array = ["A": [FruitsData(name: "apple", id: "5"), FruitsData(name: "apricot",id: "")], "M": [FruitsData(name: "mango", id: "9"),    FruitsData(name: "grapes", id: "")]]

首先, tableViewSource不是Dictionary的Array ,而是每個具有Array作為值的鍵的Dictionary 同樣從您的示例中, id不是nil而是empty如果您想刪除id為nil或為emptyFruitsData對象,可以使它像這樣。

var tableViewSource = [String : [FruitsData]]()
tableViewSource.forEach {
    let res = $1.filter { $0.id != nil && $0.id != "" }
    tableViewSource[$0] = res
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM