Junior — Middle
How do you create your own dictionary implementation?
sobes.tech AI
Answer from AI
To create a custom dictionary implementation in iOS using Swift, you can use a hash table-based data structure. The main idea is to store key-value pairs in an array of buckets, where each bucket contains a list of elements with the same hash code (to resolve collisions).
Here's a simple example of a dictionary implementation using an array and chaining:
struct MyDictionary<Key: Hashable, Value> {
private typealias Element = (key: Key, value: Value)
private var buckets: [[Element]]
private let capacity: Int
init(capacity: Int = 16) {
self.capacity = capacity
self.buckets = Array(repeating: [], count: capacity)
}
private func index(forKey key: Key) -> Int {
return abs(key.hashValue) % capacity
}
mutating func set(value: Value, forKey key: Key) {
let index = self.index(forKey: key)
// Check if an element with the same key already exists
if let i = buckets[index].firstIndex(where: { $0.key == key }) {
buckets[index][i].value = value
} else {
buckets[index].append((key, value))
}
}
func get(forKey key: Key) -> Value? {
let index = self.index(forKey: key)
return buckets[index].first(where: { $0.key == key })?.value
}
}
// Usage:
var dict = MyDictionary<String, Int>()
dict.set(value: 42, forKey: "answer")
print(dict.get(forKey: "answer") ?? "not found") // 42
This dictionary supports basic insert and search operations. For a more advanced implementation, you can add deletion, dynamic resizing, improved collision handling, etc.