Skip to content

Instantly share code, notes, and snippets.

@bwoods
Created September 14, 2018 21:51
Show Gist options
  • Save bwoods/62a62e653f1fb6413f5989b61fdb077a to your computer and use it in GitHub Desktop.
Save bwoods/62a62e653f1fb6413f5989b61fdb077a to your computer and use it in GitHub Desktop.

Multimap.swift

Being able to insert into a Dictionary<Key, Array<Values>> without having to explicitly handle the fact that the value array is nil on the very first insert for a given key.

The code isn't difficult, but it is repetitive boilerplate. And it is also a decent example of extending a generic type in Swift.

import Foundation
extension Dictionary where Value: RangeReplaceableCollection {
/// Append a new value to a Dictionary being treated as a multimap. The dictionary can map to any `RangeReplaceableCollection` (of values).
mutating func append(_ value: Value.Element, for key: Dictionary.Key) {
var array = self[key]
if array == nil {
array = Value() // RangeReplaceableCollection includes an init() requirement: see https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20161219/029658.html
self[key] = array
}
array!.append(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment