Junior
Jak byste implementovali slovník ve Swiftu pomocí pole?
sobes.tech AI
Odpověď od AI
Použijte strukturu nebo třídu k reprezentaci párů "klíč-hodnota" a poté tyto struktury/třídy uložte do pole.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Přidání nebo aktualizace hodnoty podle klíče
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Klíč nalezen, aktualizace hodnoty
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Klíč nenalezen, přidání nového páru
elements.append(KeyValuePair(key: key, value: value))
}
}
// Získání hodnoty podle klíče
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Odstranění podle klíče
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Příklad použití
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Aktualizace hodnoty pro "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Výstup: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Výstup: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Výstup: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Výstup: nil