对于Swift词典,是否有相当于NSDictionary的objectsForKeys:notFoundMarker:
?
答案 0 :(得分:4)
事实上,Martin R建议使用map()
是一个很好的方法,而且非常好!
myKeys.map({ myDict[$0] })
将返回一组可选项!
答案 1 :(得分:-1)
extension Dictionary {
public subscript(k1: Key, k2: Key, ks: Key...) -> [Value?] {
get { return ([k1, k2] + ks).map { k in self[k] } }
set { for (k, v) in zip([k1, k2] + ks, newValue) { self[k] = v } }
}
}
let dict = [1:"a", 2:"b", 4:"d"]
dict[1, 2, 3, 4] // ["a", "b", nil, "d"]