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