Sobes.tech
Junior

Hogyan valósítanád meg egy szótárat Swift-ben egy tömb használatával?

sobes.tech MI

Válasz az MI-től

Használjon egy struktúrát vagy osztályt a "kulcs-érték" párok ábrázolására, majd ezeket a struktúrákat/osztályokat tárolja egy tömbben.

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

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

    // Érték hozzáadása vagy frissítése kulcs szerint
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Kulcs megtalálva, érték frissítése
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Kulcs nem található, új pár hozzáadása
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Érték lekérése kulcs szerint
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Törlés kulcs szerint
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Használati példa
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Érték frissítése "a"-hoz

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

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