Last active
November 15, 2016 16:00
-
-
Save russbishop/8f7e69bcd0aa8285b4496e1f3d5340e1 to your computer and use it in GitHub Desktop.
Append to array inside a dictionary without copying
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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