Tom G
Tom G

Reputation: 133

How to create alphabetic sections in TableView with header from MutableArray using swift 3

I'm trying to add sections to my table but I can't manage to get my fist letter from my MutableArray (my database that contain 60 values) into a dictionary. I want to create alphabetic sections with the first letter as the header and the number of rows in sections as all the values that start with that letter.

my code:

func getSectionsFromData() -> Dictionary<Character,String> {

    var sectionDictionary = Dictionary<Character, String>()

    let crime: CrimesInfo = marrCrimesNames.object(at: 0) as! CrimesInfo
    var crimeFirstLetter: AnyObject
    let crimeName = crime.Name

    for crime in marrCrimesNames {
        crimeFirstLetter = crimeName.characters.first! as AnyObject
        print(crimeFirstLetter)
    }
    return sectionDictionary
}

Output:

"A" // 60 times

Upvotes: 0

Views: 1425

Answers (1)

Sergey Katranuk
Sergey Katranuk

Reputation: 1182

In

for crime in marrCrimesNames {
    crimeFirstLetter = crimeName.characters.first! as AnyObject
    print(crimeFirstLetter)
}

You're not actually using the crime variable Instead you're using only crimeName that's why you're getting "A" all the time.

Try instead

for crime in marrCrimesNames {
    crimeFirstLetter = crime.Name.characters.first! as AnyObject
    print(crimeFirstLetter)
}

Now to create a dictionary like this:

let dict = ["A" : ["Aname1", "Aname2", "Aname3"], "B" : ["Bname1", "Bname2", "Bname3"]]

from an array like this:

let array = ["Aname1", "Aname2", "Aname3", "Bname1", "Bname2", "Bname3"]

You can use this code:

let dict = ["A" : ["Aname1", "Aname2", "Aname3"], "B" : ["Bname1", "Bname2", "Bname3"]]

let characters = Array(Set(array.flatMap({ $0.characters.first })))

var result = [String: [String]]()

for character in characters.map({ String($0) }) {
    result[character] = array.filter({ $0.hasPrefix(character) })
}

print(result) // output: ["B": ["Bname1", "Bname2", "Bname3"], "A": ["Aname1", "Aname2", "Aname3"]]

Upvotes: 4

Related Questions