【问题标题】:Arrays as values in a Dictionary in Swift: Cannot append values数组作为 Swift 字典中的值:不能附加值
【发布时间】: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


    【解决方案1】:

    您只需要处理else 条件:

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

    【讨论】:

    • theDictionary[aCategory, default: []].append(aSomething)替换整个块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2021-04-24
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多