2017-05-27 60 views
0

我有一個像我有字典數組的情況,其中每個鍵都有特定對象的數組。喜歡這個。如何對字典數組中的數組應用過濾器?

// 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: "")]] 

回答

2

所有tableViewSource首先是不字典的Array,它是Dictionary與每個鍵具有數組作爲值。同樣來自你的例子id不是nil而是empty如果你想刪除FruitsData的對象,其ID是nilempty你可以這樣做。

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

非常感謝..它解決了我的問題。但這不是一個字典陣列? – user1960279

+0

@ user1960279歡迎隊友:)是的,它不是字典的數組,它是所有值爲字典的字典 –