Arrays Swift中字典中的数组

Arrays Swift中字典中的数组,arrays,swift,Arrays,Swift,我的问题很简单,我想这很容易做到,但是,当数组保存在Swift语言的字典中时,如何将对象添加到数组中呢 var dictionary = [String: [String]]() for course in self.category.m_course_array { let firstChar = String(Array(course.getTitle())[0]).uppercaseString dictionary[firstChar] = // How to add

我的问题很简单,我想这很容易做到,但是,当数组保存在Swift语言的字典中时,如何将对象添加到数组中呢

var dictionary = [String: [String]]()
for course in self.category.m_course_array
{
    let firstChar = String(Array(course.getTitle())[0]).uppercaseString
    dictionary[firstChar] =  // How to add an element into the array of String
}
试试这个

dictionary[firstChar].append(yourElement)

因为
dictionary[firstChar]
应该能让你得到你的数组

事实上并不像你想象的那么容易。这有点混乱,因为您需要处理这样一个事实:当密钥不存在时,您需要初始化数组。这里有一种方法(代码修改为类似但独立):

或者,如果要使用
.append
,可以执行以下操作:

    // even though .append returns no value i.e. Void, this will
    // return Optional(Void), so can be checked for nil in case
    // where there was no key present so no append took place 
    if dictionary[firstChar]?.append(course) == nil {
        // in which case you can insert a single entry
        dictionary[firstChar] = [course]
    }

这有两个问题。1) dictionary key lookup返回一个可选值,因此无法对结果调用append,您需要首先通过链接、映射或类似方式展开该可选值,并且2)需要初始化数组,然后才能对其进行追加
    // even though .append returns no value i.e. Void, this will
    // return Optional(Void), so can be checked for nil in case
    // where there was no key present so no append took place 
    if dictionary[firstChar]?.append(course) == nil {
        // in which case you can insert a single entry
        dictionary[firstChar] = [course]
    }