在Swift中将由region_name分隔的部分添加到UITableView

时间:2018-11-09 06:53:59

标签: swift swift3 swift4

我有一些从数据库中获取的JSON数据。我可以将其拉细并加载到我的表格视图中。我的问题是分离我的JSON数据,所以我可以对tableview进行分区。我有这样的JSON数组

"data": [
            {
                "ID": 1,
                "wilayah_id": 1,
                "name": "Jembatan Lima",
                "region_name": "region1"
            },
            {
                "ID": 2,
                "wilayah_id": 1,
                "name": "Kebon Jeruk",
                "region_name": "region1"
            },
            {
                "ID": 18,
                "wilayah_id": 3,
                "name": "Waylunik",
                "region_name": "region2"
            },
            {
                "ID": 19,
                "wilayah_id": 3,
                "name": "Tenggiri",
                "region_name": "region2"
            },
            {
                "ID": 25,
                "wilayah_id": 3,
                "name": "Mesuji",
                "region_name": "region3"
            },
            {
                "ID": 26,
                "wilayah_id": 4,
                "name": "KM 6",
                "region_name": "region3"
            }
  ]

我想做的就是将这些数据分成三部分,在我的表格视图中按“ region_name”排序。

1 个答案:

答案 0 :(得分:0)

//region model

struct RegionList {
  var ID:String
  var wilayah_id:String
  var name:String
  var region_name:String


  static var dataSource:[RegionList] {


    return [
      RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R1"),
      RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R2"),
      RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R1"),
      RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R2"),
      RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R3")

    ]
  }
}


 //Coming Json Array
var arrRegion:[RegionList] = []

//MAKe Section Array by Using Model Class
var regionInSectionArray:[[RegionList]] = []


//Using Dic key in String and value is Model
var usingDicKeySectionArray:[String:[RegionList]] = [:]

// Dummy Data
arrRegion = RegionList.dataSource


//Using Default Dictionary Method to make a group
usingDicKeySectionArray = Dictionary.init(grouping: arrRegion, by: { (region) -> String in

  /// Here we are making group dictionary by using region name, you can set by own requirment

  //Specify by Region
  return region.region_name
})

// You can use it in number of section usingDicKeySectionArray.count
//And number of rowInSection usingDicKeySectionArray[section].count

print(usingDicKeySectionArray.map{$0.key})
//end


///Sorting Keys
//Second option
let sortedKeys = usingDicKeySectionArray.keys.sorted()
sortedKeys.forEach { (key) in

  //
  let region = usingDicKeySectionArray[key]
  regionInSectionArray.append(region ?? [])
}



//USe

//regionInSectionArray.count // in numberOfSection
//regionInSectionArray[section].count // in numberOfRowInSection

//result  = ["R1", "R2", "R3"]