title: "Preloading" A Dictionary With Keys in Swift
body: <p>This is a fairly simple issue, but one I would like to solve, as it <em>MAY</em> help with performance.</p>
  
  <p>I want to find out if Swift has a way to create a Dictionary, specifying <em>ONLY</em> keys, and maybe no values, or a single value that is set in each entry.</p>
  
  <p>In other words, I want to create a Dictionary object, and "preload" its keys. Since this is Swift, the values could be 0 or nil (or whatever is a default empty).</p>
  
  <p>The reason for this, is so that I can avoid two loops, where I go through once, filling a Dictionary with keys and empty values, and a second one, where I then set those values (There's a practical reason for wanting this, which is a bit out of the scope of this question).</p>
  
  <p>Here's sort of what I'm thinking:</p>
  
  <pre><code>func gimme_a_new_dictionary(_ inKeyArray:[Int]) -&gt; [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])
  </code></pre>
  
  <p>But I'm wondering if there's a quicker way to do the same thing (as in "language construct" way -I could probably figure out a faster way to do this in a function).</p>
  
  <p><strong>UPDATE:</strong> The first solution <em>ALMOST</em> works. It works fine in Mac/iOS. However, the Linux version of Swift 3 doesn't seem to have the <a href="https://developer.apple.com/documentation/swift/dictionary/2894798-init" rel="nofollow noreferrer">uniqueKeysWithValues</a> initializer, which is annoying.</p>
  
  <pre><code>func gimme_a_new_dictionary(_ inKeyArray:[Int]) -&gt; [Int:Int] {
      return Dictionary&lt;Int,Int&gt;(uniqueKeysWithValues: inKeyArray.map {($0, 0)})
  }
  
  let test1 = gimme_a_new_dictionary([4,6,1,3,0,1000])
  </code></pre>