似乎应该有一个简单的方法:

for each token
   look it up in a dictionary
   if it's there already, increment the value by 1
   else create it and set value to 1

我可以用它
for token in tokens {
    if let count = myDict[token] {
        myDict[token] = count + 1
    } else {
        myDict[token] = 1
}

但似乎必须有一种更优雅、更单一的方式来做到这一点?

最佳答案

可以使用三元运算符:

for token in tokens {
    myDict[token] = myDict[token] ? myDict[token]! + 1 : 1
}

更好的方法是,使用零合并:
for token in tokens {
    myDict[token] = (myDict[token] ?? 0) + 1
}

把整件事放在一条线上:
tokens.forEach { myDict[$0] = (myDict[$0] ?? 0) + 1  }

使用Swift 4(感谢Hamish),它可以稍微短一点:
tokens.forEach { myDict[$0, default: 0] += 1 }

关于swift - 单行:快速创建Dict键或更新计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47658408/

10-11 06:16
查看更多