title: Build a Dictionary with reduce in Swift
body: <p>I am trying to use the Swift <code>reduce</code> to build a dictionary from collections in Swift .
  I have the following variables:</p>
  
  <pre><code>var _squares  : [String] = []
  var _unitlist : [[String]] = []
  var _units    = [String: [[String]]]()
  </code></pre>
  
  <p>I want to fill the <code>_units</code> dictionary int the following way: </p>
  
  <ul>
  <li>I want to iterate over every element in <code>_squares</code></li>
  <li>I want to look at all the lists in <code>_unitlist</code> and filter only the ones that contain the element</li>
  <li>Build a dictionary that has every single element as a key and the list of lists containing such element as value.</li>
  </ul>
  
  <p>To give you an example. If we have:</p>
  
  <pre><code>squares = ["A"]
  unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
  </code></pre>
  
  <p>the expected output should be a dictionary di "A" as key and <code>[["A", "B", "C"], ["A", "C"]]</code> as value.</p>
  
  <p>I tried with something like this:</p>
  
  <pre><code>_units = _squares.flatMap { s in
      _unitlist.flatMap { $0 }.filter {$0.contains(s)}
          .reduce([String: [[String]]]()){ (dict, list) in
              dict.updateValue(l, forKey: s)
              return dict
      }
  }
  </code></pre>
  
  <p>I used <code>flatMap</code> twice to iterate, then I filtered and I tried to use <code>reduce</code>.</p>
  
  <p>However, with this code I am facing the following error: <code>Cannot assign value of type '[(key: String, value: [[String]])]' to type '[String : [[String]]]'</code> that is a bit obscure to me.</p>