Sobes.tech
Junior

How would you implement a dictionary in Swift using an array?

sobes.tech AI

Answer from AI

Using a structure or class to represent "key-value" pairs and then storing these structures/classes in an array.

struct KeyValuePair<Key, Value> {
    let key: Key
    let value: Value
}

struct ArrayBasedDictionary<Key: Equatable, Value> {
    private var elements: [KeyValuePair<Key, Value>] = []

    // Add or update value by key
    mutating func setValue(_ value: Value, forKey key: Key) {
        if let index = elements.firstIndex(where: { $0.key == key }) {
            // Key found, update value
            elements[index] = KeyValuePair(key: key, value: value)
        } else {
            // Key not found, add new pair
            elements.append(KeyValuePair(key: key, value: value))
        }
    }

    // Get value by key
    func getValue(forKey key: Key) -> Value? {
        return elements.first(where: { $0.key == key })?.value
    }

    // Remove by key
    mutating func removeValue(forKey key: Key) {
        elements.removeAll(where: { $0.key == key })
    }
}

// Example usage
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Update value for "a"

print(myDictionary.getValue(forKey: "a") ?? "nil") // Output: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Output: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Output: nil

myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Output: nil
How would you implement a dictionary in Swift using… - sobes.tech