swift 4 拆分数组和过滤器

swift 4 split array and filter

我将构建一个带有部分的 UICollectionView。 这些部分基于 json.category 中的 return 值。

json 格式如下:

[{"id":"1",
  "name":"Apple",
  "category":"Fruits"},
{"id":"2",
 "name":"Pie",
 "category":"Fruits"},
{"id":"3",
 "name":"Tomato",
 "category":"Vegetable"}]

我需要一个数组过滤器,数组类似于:(对于 sectionsItems 和 sectionNames)

CategorieNames[STRING] = ["Fruits","Vegetable"] // the section names from json.category
Fruits = [STRING] = ["Apple","Pie"]
Vegetables = [STRING] = ["Tomato"]

Categories.append[Fruits]
Categories.append[Vegetables]

Categories[[STRING]] = [[Fruits],[Vegetable]]

试试下面的代码。

        let arrData = [["id": "1",
                        "name": "Apple",
                        "category": "Fruit"],
                       ["id": "2",
                        "name": "Pie",
                        "category": "Fruit"],
                       ["id": "3",
                        "name": "Tomato",
                        "category": "Vegetable"]]

        let categorieNames = Array(Set(arrData.map({[=10=]["category"]!})))
        var arrResult:[[String]] = []
        for i in 0..<categorieNames.count {

            let categories = arrData.filter({[=10=]["category"] == categorieNames[i]}).map({[=10=]["name"]!})
            arrResult.append(categories)
        }
        print("result : \(arrResult)")

result : [["Apple", "Pie"], ["Tomato"]]

您可以按照以下方式进行:

let arrData = [["id": "1",
                "name": "Apple",
                "category": "Fruit"],

               ["id": "2",
                "name": "Pie",
                "category": "Fruit"],

               ["id": "3",
                "name": "Tomato",
                "category": "Vegetable"]]



var categorys = [[String]]()
var fruits = [String]()
var vegetable = [String]()

for data in arrData {

     if let category = data["category"] {
          if category == "Fruit"{
               if let aFruit = data["name"] {
                    fruits.append(aFruit)
               }
          }
          else if category == "Vegetable" {
               if let aVeggeie = data["name"] {
                     vegetable.append(aVeggeie)
               }
          }


}
}
categorys.append(fruits)
categorys.append(vegetable)