我想要一个函数将对象 Something append 到 Somethings 数组,作为字典中的值。如果 key 不存在,我想创建它。如果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
}
}
最佳答案
你只需要处理else
条件:
if var arrayOfSomethings = theDictionary[aCategory]{
arrayOfSomethings.append(aSomething)
theDictionary[aCategory] = arrayOfSomethings
} else {
theDictionary[aCategory] = [aSomething]
}
关于数组作为 Swift 字典中的值 : Cannot append values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011889/