Junior
Jak zaimplementowałbyś słownik w Swift za pomocą tablicy?
sobes.tech AI
Odpowiedź od AI
Używając struktury lub klasy do reprezentowania par "klucz-wartość" i następnie zapisując te struktury/klasy w tablicy.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Dodanie lub aktualizacja wartości po kluczu
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Klucz znaleziony, aktualizujemy wartość
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Klucz nie znaleziony, dodaj nową parę
elements.append(KeyValuePair(key: key, value: value))
}
}
// Pobranie wartości po kluczu
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Usunięcie po kluczu
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Przykład użycia
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Aktualizacja wartości dla "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Wydruk: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Wydruk: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Wydruk: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Wydruk: nil