简体   繁体   中英

How do I group Dictionary Data with Swift

I have my dictionary data in this format.

var data: [[String:AnyObject]] =

[
  [
    "id": "1",
    "title": "A Title",
    "Detail": "This is a String"
  ],      
  [
    "id": "2",
    "title": "A Title Again",
    "Detail": "This is a String"
  ],
  [
    "id": "3",
    "title": "B Title",
    "Detail": "This is a String"
  ],
  [
    "id": "4",
    "title": "B Title Again",
    "Detail": "This is a String"
  ]
]

Does anyone have an idea how I can group my tableView from [AZ] like the prototype image below with Swift.

原型

This is a two step problem (that we'll solve in pure Swift). First, we need to determine what sections we have (in this case, just A and B . This is fairly simple:

var letters = Set<String>()

for element in data {
    var title = element["title"] as? String
    let letter = title?.substringToIndex(advance(title!.startIndex, 1))

    letters.insert(letter!)
}

We first create a set of String objects, so that each letter is represented just once. To get the first character (in pure Swift), we must use substringToIndex and pass in a String.Index value using advance . As a side note, if you'd like to normalize the letters, append .uppercaseString before inserting the letter into letters .

print(letters) will then output [A, B] .

––

Secondly, we need to sort data by the title key. Swift makes sorting quite easy:

data.sort { element1, element2 in
    let title1 = element1["title"] as? String
    let title2 = element2["title"] as? String

    return title1 < title2
}

You can then arrange the data however you like, now knowing how to both sort by key, and detect which letters to show. Hope this helps!

You want the UITableViewDataSource API.

The table that your image shows is a plain table view with titles and sections.

Some of the methods you want to implement are numberOfSectionsInTableView and titleForHeaderInSection . For the scrollable index alongside the table, you want sectionIndexTitlesForTableView . All of these methods are described in the link above.

You may consider sorting your array and breaking it up by letter of the alphabet, but doing so can be expensive, so don't do it while your user is scrolling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM