Sobes.tech
Junior

Kuidas te implementiksite Swiftis sõnastiku, kasutades massiivi?

sobes.tech AI

Vastus AI-lt

Kasutades struktuuri või klassi "võti-väärtus" paaride esitamiseks ning seejärel nende struktuuride/klasside salvestamiseks massiivis.

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

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

    // Väärtuse lisamine või uuendamine võtme järgi
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Võti leitud, uuendame väärtust
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Võti ei leidu, lisame uue paari
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Väärtuse saamine võtme järgi
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Kustutamine võtme järgi
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Näide kasutamisest
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Väärtuse uuendamine "a" jaoks

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

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Väljund: nil