Sobes.tech
Junior

Kako biste implementirali rečnik u Swift-u koristeći niz?

sobes.tech АИ

Одговор од АИ

Koristite strukturu ili klasu za predstavljanje parova "ključ-vrednost" i zatim te strukture/klase sačuvajte u nizu.

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

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

    // Dodavanje ili ažuriranje vrednosti po ključu
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Ključ pronađen, ažurirajte vrednost
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Ključ nije pronađen, dodajte novi par
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Dobijanje vrednosti po ključu
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Brisanje po ključu
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Primer upotrebe
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Ažuriranje vrednosti za "a"

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

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Izlaz: nil