【问题标题】:"Preloading" A Dictionary With Keys in Swift在 Swift 中“预加载”带有键的字典
【发布时间】:2017-11-04 12:11:13
【问题描述】:

这是一个相当简单的问题,但我想解决一个问题,因为它可能有助于提高性能。

我想知道 Swift 是否有办法创建字典,指定 ONLY 键,可能没有值,或者在每个条目中设置一个值。

换句话说,我想创建一个 Dictionary 对象,并“预加载”它的键。由于这是 Swift,因此值可以是 0 或 nil(或默认为空的任何值)。

这样做的原因是,我可以避免两个循环,我通过一次,用键和空值填充字典,然后在第二个循环中设置这些值(有一个实际的原因想要this,这有点超出了这个问题的范围)。

以下是我的想法:

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])

但我想知道是否有更快的方法来做同样的事情(如“语言构造”方式 - 我可能会找到一种更快的方法来在函数中执行此操作)。

更新:第一个解决方案几乎有效。它在 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])

【问题讨论】:

  • init(uniqueKeysWithValues:)Dictionary 初始化器确实是 Swift 4.0 的特性。
  • 啊!这就是为什么!没关系,那么...
  • 阅读理解。我听说过...

标签: ios arrays swift dictionary


【解决方案1】:

对于 Swift 4,您可以使用接受序列的字典构造函数并使用 map 从您的键数组中创建元组序列:

let dict = Dictionary(uniqueKeysWithValues: [4,6,1,3,0,1000].map {($0, 0)})

【讨论】:

  • 这看起来像是一个答案。我会把它扔进我的搅拌机里,看看它是否能奏效。它可能会被 map() 的性能所缓解。
  • 它可能不会比你的方法快,因为map 实际上只是一个循环。我想这取决于你的目标是什么。
  • 谢谢!看我的更新。它适用于 Mac,但不适用于 Linux。然而,你是对的。它可能不会更快。也就是说,我会假设像 map() 这样的内置函数已经优化了 yin-yang。
【解决方案2】:

我认为您可以通过在初始化期间指定最小容量来优化您的代码分配。但是,一个班轮可能是上述答案,它本质上是分配和循环以在每个位置添加 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-25
    • 2018-10-19
    • 2021-09-27
    • 2019-11-26
    • 2015-05-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多