Junior
Come implementeresti un dizionario in Swift usando un array?
sobes.tech AI
Risposta dell'AI
Utilizzando una struttura o una classe per rappresentare coppie "chiave-valore" e poi memorizzando queste strutture/classe in un array.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Aggiungi o aggiorna il valore per la chiave
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Chiave trovata, aggiorna il valore
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Chiave non trovata, aggiungi una nuova coppia
elements.append(KeyValuePair(key: key, value: value))
}
}
// Ottieni il valore per la chiave
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Rimuovi per chiave
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Esempio di utilizzo
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Aggiorna il valore per "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Output: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Output: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Output: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Output: nil