Sobes.tech
Junior

Kaip įgyvendintumėte žodyną Swift naudojant masyvą?

sobes.tech AI

Atsakymas iš AI

Naudokite struktūrą arba klasę, kad atstovautumėte "raktas-reikšmė" poras, ir tada šias struktūras/klases saugokite masyve.

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

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

    // Pridėti arba atnaujinti reikšmę pagal raktą
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Raktas rastas, atnaujinkite reikšmę
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Raktas nerastas, pridėkite naują porą
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Gauti reikšmę pagal raktą
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Pašalinti pagal raktą
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Pavyzdys
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Atnaujinti reikšmę "a"

print(myDictionary.getValue(forKey: "a") ?? "nil") // Išvestis: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Išvestis: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Išvestis: nil

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Išvestis: nil