首页 文章

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

提问于
浏览
0

我想要一个函数将一个对象附加到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 回答

  • 2

    您只需要处理 else 条件:

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

相关问题