Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@russbishop
Last active November 15, 2016 16:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russbishop/8f7e69bcd0aa8285b4496e1f3d5340e1 to your computer and use it in GitHub Desktop.
Save russbishop/8f7e69bcd0aa8285b4496e1f3d5340e1 to your computer and use it in GitHub Desktop.
Append to array inside a dictionary without copying
/// Appends a value to an array within a dictionary without triggering a copy.
/// Necessary in Swift 3 but expected to be obsoleted as the way inout works
/// will be changed (eliminating the need for the write-back copy)
func append<K, V>(value: V, toKey key: K, in dict: inout [K : Array<V>]) {
var a: [V]? = []
swap(&a, &dict[key])
a = a ?? []
a!.append(value)
swap(&a, &dict[key])
}
/// Removes a value from an array within a dictionary without triggering a copy.
@discardableResult
func remove<K, V>(value: V, fromKey key: K, in dict: inout [K: Array<V>]) -> Bool where V: Equatable {
var a: [V]? = []
swap(&a, &dict[key])
a = a ?? []
let result = a!.removeElement(value)
swap(&a, &dict[key])
return result
}
/// Removes an index from an array within a dictionary without triggering a copy.
func remove<K, V>(index: Int, fromKey key: K, in dict: inout [K: Array<V>]) where V: Equatable {
var a: [V]? = []
swap(&a, &dict[key])
a = a ?? []
a!.remove(at: index)
swap(&a, &dict[key])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment