Junior
Kā jūs realizētu vārdnīcu Swift, izmantojot masīvu?
sobes.tech AI
Atbilde no AI
Izmantojiet struktūru vai klasi, lai attēlotu "atslēgas-vērtības" pārus, un pēc tam saglabājiet šīs struktūras/klases masīvā.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Pievienot vai atjaunināt vērtību pēc atslēgas
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Atslēga atrasta, atjauniniet vērtību
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Atslēga nav atrasta, pievienojiet jaunu pāri
elements.append(KeyValuePair(key: key, value: value))
}
}
// Iegūt vērtību pēc atslēgas
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Dzēst pēc atslēgas
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Piemērs
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Atjaunināt vērtību "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Izvade: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Izvade: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Izvade: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Izvade: nil