【发布时间】:2017-08-18 02:57:22
【问题描述】:
我想要一个函数将对象Something附加到Somethings数组中,作为字典中的值。如果密钥不存在,我想创建它。如果theDictionary[aCategory]为空,则不会进入if var语句(因为是nil),所以我真的不知道怎么做解决它。我确信通过强制展开我会解决它,但我真的想使用更安全的方式,比如可选投标。
private var theDictionary: [Category:[Something]] = [:]
public func add(aSomething: Something, aCategory: Category{
if var arrayOfSomethings = theDictionary[aCategory]{
arrayOfSomethings.append(aSomething)
theDictionary[aCategory] = arrayOfSomethings
}
}
【问题讨论】:
标签: arrays swift dictionary append