Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

swift - Appending to dictionary of [character: [object]] returns 0 key/value pair

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
        }

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...