附加到[character:[object]]的字典将返回0个键/值对 [英] Appending to dictionary of [character: [object]] returns 0 key/value pair

查看:86
本文介绍了附加到[character:[object]]的字典将返回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)
}

此后,我应该让我的friends数组包含名称的第一个字母和其中的用户;但是,我的朋友词典是空的.

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.

我该如何解决?

我正在学习本教程,但他并不完全一样..

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

推荐答案

使用String而不是使用Character作为键.您需要确保为插入到groupedNames中的每个新的"First Initial"键初始化[User]数组.我保留了一个groupedLetters数组,以便更轻松地获取部分计数

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

    }
}

这篇关于附加到[character:[object]]的字典将返回0个键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆