Sobes.tech
Junior

Swiftda massivdan foydalanib lug‘atni qanday amalga oshirasiz?

sobes.tech AI

AIdan javob

Kalit-qiymat juftlarini ifodalash uchun tuzilma yoki sinfdan foydalaning va keyin bu tuzilma/sinfni massivga saqlang.

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

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

    // Kalit bo'yicha qiymatni qo'shish yoki yangilash
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Kalit topildi, qiymatni yangilash
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Kalit topilmadi, yangi juftlik qo'shish
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Kalit bo'yicha qiymatni olish
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Kalit bo'yicha o'chirish
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Foydalanish misoli
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // "a" uchun qiymatni yangilash

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

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