title: Swift Dictionary default value
body: <p>A pattern I've gotten used to with Python's defaultdicts is a dictionary that returns a default value if the value for a given key has not been explicitly set. Trying to do this in Swift is a little verbose.</p>
  
  <pre><code>var dict = Dictionary&lt;String, Array&lt;Int&gt;&gt;()
  let key = "foo"
  var value: Array&lt;Int&gt;! = dict[key]
  if value == nil {
      value = Array&lt;Int&gt;()
      dict[key] = value
  }
  </code></pre>
  
  <p>I realize I can make a class that does this, but then the actual Dictionary has to be accessed through a property to use any of the other normal Dictionary methods</p>
  
  <pre><code>class DefaultDictionary&lt;A: Hashable, B&gt; {
      let defaultFunc: () -&gt; B
      var dict = Dictionary&lt;A, B&gt;()
  
      init(defaultFunc: () -&gt; B) {
          self.defaultFunc = defaultFunc
      }
      subscript(key: A) -&gt; B {
          get {
              var value: B! = dict[key]
              if value == nil {
                  value = defaultFunc()
                  dict[key] = value
              }
              return value
          }
          set {
              dict[key] = newValue
          }
      }
  }
  </code></pre>
  
  <p>Is there a better pattern for this?</p>