繁体   English   中英

在Swift中用键“预加载”字典

[英]“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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM