Sobes.tech
Junior

Ako by ste implementovali slovník v Swift pomocou poľa?

sobes.tech AI

Odpoveď od AI

Použite štruktúru alebo triedu na reprezentáciu párov "kľúč-hodnota" a potom tieto štruktúry/triedy uložte do poľa.

struct KeyValuePair<Key, Value> {
    let key: Key
    let value: Value
}

struct ArrayBasedDictionary<Key: Equatable, Value> {
    private var elements: [KeyValuePair<Key, Value>] = []

    // Pridanie alebo aktualizácia hodnoty podľa kľúča
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Kľúč nájdený, aktualizujte hodnotu
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Kľúč nenájdený, pridajte nový pár
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Získanie hodnoty podľa kľúča
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Odstránenie podľa kľúča
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Príklad použitia
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Aktualizácia hodnoty pre "a"

print(myDictionary.getValue(forKey: "a") ?? "nil") // Výstup: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Výstup: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Výstup: nil

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Výstup: nil