[英]“Preloading” A Dictionary With Keys in Swift
這是一個相當簡單的問題,但是我想解決,因為它可能對性能有所幫助。
我想找出Swift是否有辦法創建一個Dictionary, 只指定鍵,也許沒有值,或者在每個條目中設置一個值。
換句話說,我想創建一個Dictionary對象,並“預加載”它的鍵。 由於這是Swift,因此值可以為0或nil(或默認為空)。
這樣做的原因是,我可以避免兩個循環,在該循環中,我要經歷一次,用鍵和空值填充一個Dictionary,然后在第二個循環中,然后設置這些值(這是一個實際的原因,有點超出這個問題的范圍)。
這是我的想法:
func gimme_a_new_dictionary(_ inKeyArray:[Int]) -> [Int:Int] {
var ret:[Int:Int] = [:]
for key in inKeyArray {
ret[key] = 0
}
return ret
}
let test1 = gimme_a_new_dictionary([4,6,1,3,0,1000])
但是我想知道是否有一種更快的方法來完成相同的事情(如“語言構造”方法一樣-我可能想出了一種在函數中執行此操作的更快方法)。
更新:第一個解決方案ALMOST起作用。 在Mac / iOS中可以正常工作。 但是,Linux版本的Swift 3似乎沒有uniqueKeysWithValues初始化程序,這很煩人。
func gimme_a_new_dictionary(_ inKeyArray:[Int]) -> [Int:Int] {
return Dictionary<Int,Int>(uniqueKeysWithValues: inKeyArray.map {($0, 0)})
}
let test1 = gimme_a_new_dictionary([4,6,1,3,0,1000])
對於Swift 4,您可以使用采用序列的字典構造函數,並使用map
根據鍵數組創建元組序列:
let dict = Dictionary(uniqueKeysWithValues: [4,6,1,3,0,1000].map {($0, 0)})
我假設您可以通過在初始化期間指定最小容量來優化代碼的分配。 但是,上面的答案可能是一個襯線,本質上是分配和循環以在每個位置加0。
func gimme_a_new_dictionary(_ inKeyArray:[Int], minCapacity: Int) -> [Int:Int] {
var ret = Dictionray<Int, Int>(minimumCapacity: minCapacity)
for key in inKeyArray {
ret[key] = 0
}
return ret
}
let test1 = gimme_a_new_dictionary([4,6,1,3,0,1000])
看一下這個官方文檔:
/// Use this initializer to avoid intermediate reallocations when you know
/// how many key-value pairs you are adding to a dictionary. The actual
/// capacity of the created dictionary is the smallest power of 2 that
/// is greater than or equal to `minimumCapacity`.
///
/// - Parameter minimumCapacity: The minimum number of key-value pairs to
/// allocate buffer for in the new dictionary.
public init(minimumCapacity: Int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.