数组中的数组作为Swift中的字典:不能附加值

时间:2017-03-25 02:32:51

标签: arrays swift dictionary append

我想要一个函数将一个对象附加到Somethings数组中,作为Dictionary中的值。如果密钥不存在,我想创建它。如果 theDictionary [aCategory] ​​为空,则不会输入 if var 语句(因为 nil ),所以我真的不知道知道如何解决它。我确信用力展开我会解决它,但我真的想用一种更安全的方式,比如可选的biding。

private var theDictionary: [Category:[Something]] = [:]
public func add(aSomething: Something, aCategory: Category{
    if var arrayOfSomethings = theDictionary[aCategory]{
        arrayOfSomethings.append(aSomething)
        theDictionary[aCategory] = arrayOfSomethings
    }
}

1 个答案:

答案 0 :(得分:2)

您只需要处理else条件:

if var arrayOfSomethings = theDictionary[aCategory]{
    arrayOfSomethings.append(aSomething)
    theDictionary[aCategory] = arrayOfSomethings
} else {
    theDictionary[aCategory] = [aSomething]
}