大佬教程收集整理的这篇文章主要介绍了Swiftier Swift用于“添加阵列,或者如果不存在则创建……”,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
var x:[String:[Thing]] = [:]
x[which].append(t)
你必须
if x.index(forKey: which) == nil { x[which] = [] } x[which]!.append(s!)
真的,有一种更快捷的说法
x[index?!?!].append??(s?!)
从Swift 4开始,字典有一个subscript(_:default:)
方法,所以
Dict[key,default: []].append(newElement)
追加到已存在的数组或空数组.例:
var Dict: [String: [Int]] = [:] print(Dict["foo"]) // nil Dict["foo",default: []].append(1) print(Dict["foo"]) // Optional([1]) Dict["foo",default: []].append(2) print(Dict["foo"]) // Optional([1,2])
从Swift 4.1(目前处于测试版)开始,这也很快,
比较Hamish的评论here.
以前的答案为Swift< = 3:据我所知 - 没有办法“创建或更新”字典
使用单个下标调用的值.
除了你写的内容,你可以使用Nil-coalescing运算符
Dict[key] = (Dict[key] ?? []) + [elem]
或可选链接(如果追加操作,则返回nil
无法执行):
if Dict[key]?.append(elem) == nil { Dict[key] = [elem] }
正如SE-0154 Provide Custom Collections for Dictionary Keys and Values中提到的那样,也是@Hamish在评论中提到的两种方法
制作一个数组的副本.
随着SE-0154的实施,您将能够变异
没有复制的字典值:
if let i = Dict.index(forKey: key) { Dict.values[i].append(elem) } else { Dict[key] = [key] }
目前,Rob Napier提供了最有效的解决方案
在Dictionary in Swift with Mutable Array as value is performing very slow? How to optimize or construct properly?:
var array = Dict.removeValue(forKey: key) ?? [] array.append(elem) Dict[key] = array
let numKeys = 1000 let numElements = 1000 do { var Dict: [Int: [Int]] = [:] let start = Date() for key in 1...numKeys { for elem in 1...numElements { if Dict.index(forKey: key) == nil { Dict[key] = [] } Dict[key]!.append(elem) } } let end = Date() print("Your method:",end.timeIntervalSince(start)) } do { var Dict: [Int: [Int]] = [:] let start = Date() for key in 1...numKeys { for elem in 1...numElements { Dict[key] = (Dict[key] ?? []) + [elem] } } let end = Date() print("Nil coalescing:",end.timeIntervalSince(start)) } do { var Dict: [Int: [Int]] = [:] let start = Date() for key in 1...numKeys { for elem in 1...numElements { if Dict[key]?.append(elem) == nil { Dict[key] = [elem] } } } let end = Date() print("Optional chaining",end.timeIntervalSince(start)) } do { var Dict: [Int: [Int]] = [:] let start = Date() for key in 1...numKeys { for elem in 1...numElements { var array = Dict.removeValue(forKey: key) ?? [] array.append(elem) Dict[key] = array } } let end = Date() print("Remove and add:",end.timeIntervalSince(start)) }
1000键/ 1000个元素的结果(在1.2 GHz Intel Core m5 MACBook上):
Your method: 0.470084965229034 Nil coalescing: 0.460215032100677 Optional chaining 0.397282958030701 Remove and add: 0.160293996334076
对于1000个键/ 10,000个元素:
Your method: 14.6810429692268 Nil coalescing: 15.1537700295448 Optional chaining 14.4717089533806 Remove and add: 1.54668599367142
以上是大佬教程为你收集整理的Swiftier Swift用于“添加阵列,或者如果不存在则创建……”全部内容,希望文章能够帮你解决Swiftier Swift用于“添加阵列,或者如果不存在则创建……”所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。