Junior
Swift-də array istifadə edərək sözlük necə həyata keçirərdiniz?
sobes.tech Süni İntellekt
AI-dan cavab
Açar-dəyər cütlərini təmsil etmək üçün struktur və ya sinifdən istifadə edin və sonra bu strukturları/sinifləri massivdə saxlayın.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Açar ilə dəyəri əlavə edin və ya yeniləyin
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Açar tapıldı, dəyəri yeniləyin
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Açar tapılmadı, yeni cüt əlavə edin
elements.append(KeyValuePair(key: key, value: value))
}
}
// Açar ilə dəyəri alın
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Açar ilə silin
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// İstifadə nümunəsi
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // "a" üçün dəyəri yeniləyin
print(myDictionary.getValue(forKey: "a") ?? "nil") // Çıxış: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Çıxış: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Çıxış: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Çıxış: nil