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