Junior
Como implementaria um dicionário em Swift usando um array?
sobes.tech IA
Resposta da IA
Usando uma estrutura ou classe para representar pares "chave-valor" e depois armazenando essas estruturas/classes numa matriz.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Adicionar ou atualizar valor por chave
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Chave encontrada, atualizar valor
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Chave não encontrada, adicionar nova par
elements.append(KeyValuePair(key: key, value: value))
}
}
// Obter valor por chave
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Remover por chave
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Exemplo de uso
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Atualizar valor para "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Saída: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Saída: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Saída: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Saída: nil