0

I'm trying to show a tableview similar to contacts with my list of users.

I declare a global variable of friends that will store the first character of a name and a list of users whose first name start with that

var friends = [Character: [User]]()

In my fetch method, I do this

for friend in newFriends {                      
    let letter = friend.firstName?[(friend.firstName?.startIndex)!]
    print(letter)                    
    self.friends[letter!]?.append(friend)
}

After this, I should have my friends array with the first letter of the name and the users that fall in it; however, my friends dictionary is empty.

How do I fix this?

Edit: I'm following this tutorial and he doesnt exactly the same.. Swift: How to make alphabetically section headers in table view with a mutable data source

Community
  • 1
  • 1
Walker
  • 1,127
  • 15
  • 39

3 Answers3

0

Creating a Dictionary structure with Characters as keys & values as Array of User will be more succinct.

ystack
  • 1,785
  • 12
  • 23
0

Rather than using Character as the key, use String. You need to be sure to init the [User] array for every new First Initial key you insert into groupedNames. I keep an array of groupedLetters to make it easier to get a section count

var groupedNames = [String: [User]]()
var groupedLetters = Array<String>()

func filterNames() {
    groupedNames.removeAll()
    groupedLetters.removeAll()

    for friend in newFriends {
        let index = friend.firstName.index(friend.firstName.startIndex, offsetBy: 0)
        let firstLetter = String(friend.firstName[index]).uppercased()
        if groupedNames[firstLetter] != nil {
            //array already exists, just append
            groupedNames[firstLetter]?.append(friend)
        } else {
            //no array for that letter key - init array and store the letter in the groupedLetters array
            groupedNames[firstLetter] = [friend]
            groupedLetters.append(firstLetter)
        }

    }
}
dmorrow
  • 5,152
  • 5
  • 20
  • 31
0

The error occurs because you are declaring an empty dictionary, that means you have to add a key / empty array pair if there is no entry for that character.

Consider also to consolidate the question / exclamation marks

class User {
    let firstName : String

    init(firstName : String) {
        self.firstName = firstName
    }
}


var friends = [Character: [User]]()

let newFriends = [User(firstName:"foo"), User(firstName:"bar"), User(firstName:"baz")]

for friend in newFriends {
    let letter = friend.firstName[friend.firstName.startIndex]
    if friends[letter] == nil {
        friends[letter] = [User]()
    }
    friends[letter]!.append(friend)
}
vadian
  • 274,689
  • 30
  • 353
  • 361