Sobes.tech
Junior — Middle

What data structure is well suited for modeling button or key press events?

sobes.tech AI

Answer from AI

A queue is often used to model button or key press events. It is suitable because events arrive in the order they occur and need to be processed sequentially. A queue ensures FIFO (first-in, first-out) order, which aligns with the logic of handling user events.

Example in Swift using an array as a queue:

var eventQueue: [UIEvent] = []

// Adding an event to the queue
func enqueue(event: UIEvent) {
    eventQueue.append(event)
}

// Processing an event from the queue
func dequeue() -> UIEvent? {
    guard !eventQueue.isEmpty else { return nil }
    return eventQueue.removeFirst()
}

In iOS, delegates and event handlers are also frequently used, but for internal storage and sequential processing of events, a queue is an optimal choice.