Junior
Wie würdest du ein Wörterbuch in Swift mit einem Array implementieren?
sobes.tech KI
Antwort von AI
Verwenden Sie eine Struktur oder Klasse zur Darstellung von "Schlüssel-Wert"-Paaren und speichern Sie diese Strukturen/Klassen dann in einem Array.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Hinzufügen oder Aktualisieren eines Werts nach Schlüssel
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Schlüssel gefunden, Wert aktualisieren
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Schlüssel nicht gefunden, neues Paar hinzufügen
elements.append(KeyValuePair(key: key, value: value))
}
}
// Wert nach Schlüssel abrufen
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Nach Schlüssel entfernen
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Beispiel für die Verwendung
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Aktualisieren des Werts für "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Ausgabe: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Ausgabe: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Ausgabe: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Ausgabe: nil