How do I "append" to an immutable dictionary in Swift?
<p>In Scala, the <a href="http://docs.scala-lang.org/overviews/collections/maps.html" rel="nofollow noreferrer"><code>+ (k -&gt; v)</code></a>  operator on <code>immutable.Map</code> returns a new <code>immutable.Map</code> with the contents of the original, plus the new key/value pair. Similarly, in C#, <a href="https://msdn.microsoft.com/en-us/library/dn466983(v=vs.111).aspx" rel="nofollow noreferrer"><code>ImmutableDictionary.add(k, v)</code></a> returns a new, updated <code>ImmutableDictionary</code>.</p>

<p>In Swift, however, <a href="https://developer.apple.com/reference/swift/dictionary" rel="nofollow noreferrer"><code>Dictionary</code></a> appears only to have the mutating <code>updateValue(v, forKey: k)</code> function and the mutating <code>[k:v]</code> operator. </p>

<p>I thought maybe I could play some trick with <code>flatten()</code>, but no luck:</p>

<pre><code>let updated = [original, [newKey: newValue]].flatten()
</code></pre>

<p>gets me</p>

<pre><code>Cannot convert value of type '() -&gt; FlattenCollection&lt;[[String : AnyObject]]&gt;' 
to specified type '[String : AnyObject]'
</code></pre>

<p>How do I create a new, modified immutable <code>Dictionary</code> from the contents of an existing one?</p>

<hr>

<p><strong>Update:</strong> Based on <a href="https://stackoverflow.com/a/24816788/27358">this answer</a>'s note that Swift dictionaries are value types, and <a href="https://stackoverflow.com/a/24052094/27358">this answer</a>'s mutable version, I came up with the following extension operator, but I'm not excited about it -- it seems like there must be a cleaner out-of-the-box alternative.</p>

<pre><code>func + &lt;K, V&gt;(left: [K:V], right: [K:V]) -&gt; [K:V] {
    var union = left
    for (k, v) in right {
        union[k] = v
    }
    return union
} 
</code></pre>

<p>But maybe the fact (if I understand correctly) that the immutability of Swift dictionaries is a compiler check on <code>let</code> rather than a matter of different implementation classes means this is the best that can be done?</p>

<hr>

<p><strong>Update #2:</strong> As noted in <a href="https://stackoverflow.com/a/38347069/27358">Jules's answer</a>, modifying immutable dictionaries that aren't specifically optimized to share state between copies (as Swift dictionaries aren't) presents performance problems. For my current use case (<code>AttributedString</code> attribute dictionaries, which tend to be fairly small) it may still simplify certain things enough to be worth doing, but until and unless Swift implements a shared-state immutable dictionary it's probably not a good idea in the general case -- which is a good reason not to have it as a built-in feature.</p>