Sobes.tech
Junior

Swiftте массивди колдонуп сөздүктү кантип ишке ашырмаксыз?

sobes.tech AI

AIден жооп

Ключ-баардык жуптарды көрсөтүү үчүн структураны же классты колдонуп, андан соң бул структураларды/кластарды массивге сактаңыз.

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

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

    // Ачкыч боюнча маанини кошуу же жаңыртуу
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Ачкыч табылды, маанини жаңыртуу
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Ачкыч табылган жок, жаңы жуп кошуу
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Ачкыч боюнча маанини алуу
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Ачкыч боюнча өчүрүү
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Колдонуу мисалы
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // "a" үчүн маанини жаңыртуу

print(myDictionary.getValue(forKey: "a") ?? "nil") // Чыгуу: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Чыгуу: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Чыгуу: nil

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Чыгуу: nil