单行:在swift中创建Dict键或更新计数

单行:在swift中创建Dict键或更新计数,swift,dictionary,null,key,Swift,Dictionary,Null,Key,似乎应该有一个简单的方法来做到这一点: 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] = coun

似乎应该有一个简单的方法来做到这一点:

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 }

您可以使用三元运算符:

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 }

仅供参考-将
+=
更改为
+
。已修复。感谢RMADDYYYI-将
+=
更改为
+
。已修复。感谢Swift 4中的RMADD,您可以说
myDict[token,默认值:0]+=1
。在Swift 4中,您可以说
myDict[token,默认值:0]+=1
map
不是一个好选择,因为
map
返回一个新数组(在本例中)但是不需要这个结果。
map
不是一个好的选择,因为
map
返回一个新数组(在本例中),但不需要这个结果。