Skip to content

Instantly share code, notes, and snippets.

@chriswebb09
Created May 19, 2017 20:51
Show Gist options
  • Save chriswebb09/856c741e43522ab407088812455f92c5 to your computer and use it in GitHub Desktop.
Save chriswebb09/856c741e43522ab407088812455f92c5 to your computer and use it in GitHub Desktop.
struct HashTable<Key: Hashable, Value> {
// Code added earlier
@discardableResult
mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
var itemIndex: Int
itemIndex = self.index(for: key)
for (i, element) in buckets[itemIndex].enumerated() {
if element.key == key {
let oldValue = element.value
buckets[itemIndex][i].value = value
return oldValue
}
}
buckets[itemIndex].append(HashElement(key: key, value: value))
return nil
}
@discardableResult
mutating func removeValue(for key: Key) -> Value? {
let index = self.index(for: key)
for (i, element) in buckets[index].enumerated() {
if element.key == key {
buckets[index].remove(at: i)
return element.value
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment