Назад к вопросам
Junior
93
questionbank
Как бы вы реализовали словарь в Swift с использованием массива?
Sobes Copilot
Получайте ответы в реальном времени
Ответ от нейросети
sobes.tech 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