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