Sobes.tech
Junior — Middle

How can you create your own dictionary structure in programming?

sobes.tech AI

Answer from AI

In iOS (Swift), to create a custom dictionary structure, you can define a struct or class that stores key-value pairs. For example, you can create a structure with an array of tuples or use a dictionary inside your structure and add the necessary methods.

Here's an example of a simple custom dictionary structure in Swift:

struct MyDictionary<Key: Hashable, Value> {
    private var items: [(key: Key, value: Value)] = []

    mutating func add(key: Key, value: Value) {
        if let index = items.firstIndex(where: { $0.key == key }) {
            items[index].value = value
        } else {
            items.append((key: key, value: value))
        }
    }

    func value(for key: Key) -> Value? {
        return items.first(where: { $0.key == key })?.value
    }
}

var dict = MyDictionary<String, Int>()
dict.add(key: "one", value: 1)
print(dict.value(for: "one")) // Optional(1)

This is how you can implement basic dictionary functionality on your own.