Max
Max

Reputation: 941

Indexed table view

I am a beginner in Swift, I have tried to make an Indexed table view according to this tutorial: https://www.ioscreator.com/tutorials/indexed-table-view-ios-tutorial-ios11, but I have some doubts and I would like to ask something. Here is my code so far:

 for car in cars {
        let carKey = String(car.prefix(1))
            if var carValues = carsDictionary[carKey] {
                carValues.append(car)
                carsDictionary[carKey] = carValues
            } else {
                carsDictionary[carKey] = [car]
            }
    }

    // 2
    carSectionTitles = [String](carsDictionary.keys)
    carSectionTitles = carSectionTitles.sorted(by: { $0 < $1 })

First of all, I want to make a sure that this line

if var carValues = carsDictionary[carKey]

takes all cars starting with word(carKey) from carsDictionary and store to array. If it is true, it stores the next car to the array, and put it back into the dictionary. Is it correct?

Unfortunately I don't understand what this line is doing

carSectionTitles = [String](carsDictionary.keys)

Also, I'm not sure about this function, mainly with the section "configure the cell"

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 3
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // Configure the cell...
    let carKey = carSectionTitles[indexPath.section]
    if let carValues = carsDictionary[carKey] {
        cell.textLabel?.text = carValues[indexPath.row]
    }

    return cell
}

Does it work like a loop? I am not sure about indexPath.section. Could someone explain it? Thank you in advance.

Upvotes: 1

Views: 689

Answers (1)

vadian
vadian

Reputation: 285290

The way to create the dictionary is correct but in Swift 4 there is a much more convenient way

carsDictionary = Dictionary(grouping: cars, by: {$0.prefix(1)})

The line carSectionTitles = [String](carsDictionary.keys) creates an array of the dictionary keys (the prefix letters). This line and the next line to sort the array can be written in a more efficient way:

carSectionTitles = carsDictionary.keys.sorted()

IndexPath has two components, section and row. The sections are represented by carSectionTitles and the keys in the dictionary and the rows are the values in the dictionary. cellForRowAt is called once for each row. The code gets the section from carSectionTitles and gets the rows from the dictionary. The optional binding is actually not needed because it's guaranteed that each letter has an associated array.

let carKey = carSectionTitles[indexPath.section] // carKey is one of the prefix letters
let carValues = carsDictionary[carKey]! // get the rows
cell.textLabel?.text = carValues[indexPath.row] // get the value for that particular row

Upvotes: 4

Related Questions