Junior
Cum ați implementa un dicționar în Swift folosind un array?
sobes.tech AI
Răspuns de la AI
Utilizați o structură sau o clasă pentru a reprezenta perechi "cheie-valoare" și apoi stocați aceste structuri/clase într-un array.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Adăugarea sau actualizarea valorii după cheie
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Cheia găsită, actualizează valoarea
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Cheia negăsită, adaugă un nou cuplu
elements.append(KeyValuePair(key: key, value: value))
}
}
// Obține valoarea după cheie
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Șterge după cheie
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Exemplu de utilizare
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Actualizează valoarea pentru "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Ieșire: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Ieșire: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Ieșire: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Ieșire: nil