Junior
¿Cómo implementarías un diccionario en Swift usando un array?
sobes.tech AI
Respuesta de la IA
Usando una estructura o clase para representar pares "clave-valor" y luego almacenando estas estructuras/clases en un array.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Añadir o actualizar un valor por clave
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Clave encontrada, actualizar valor
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Clave no encontrada, añadir nueva pareja
elements.append(KeyValuePair(key: key, value: value))
}
}
// Obtener valor por clave
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Eliminar por clave
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Ejemplo de uso
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Actualizar valor para "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Salida: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Salida: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Salida: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Salida: nil