Sobes.tech
Junior — Middle

Como é que você cria a sua própria implementação do dicionário?

sobes.tech IA

Resposta da IA

Para criar uma implementação própria de um dicionário em iOS com Swift, pode usar uma estrutura de dados baseada numa tabela de hash. A ideia principal é armazenar pares chave-valor numa matriz de buckets, onde cada bucket contém uma lista de elementos com o mesmo código hash (para resolver colisões).

Exemplo de uma implementação simples de um dicionário usando uma matriz e cadeias:

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)
        // Verifica se já existe um elemento com essa chave
        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
    }
}

// Uso:
var dict = MyDictionary<String, Int>()
dict.set(value: 42, forKey: "answer")
print(dict.get(forKey: "answer") ?? "not found")  // 42

Este tipo de dicionário suporta operações básicas de inserção e pesquisa. Para uma implementação mais avançada, pode adicionar remoção, expansão dinâmica, melhor tratamento de colisões, etc.