Skip to Content
Course content

181: Deque from Swift Collections Package

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Most of the time, a standard Swift Array is all you need. It's fast, familiar, and handles most lists perfectly. But the moment you find yourself calling insert(_:at: 0) inside a loop or a high-frequency function, you've hit a performance wall. Every time you push something to the front of an array, Swift has to shift every single existing element one slot to the right. That's an O(n) operation, and it will kill your app's responsiveness if the list grows.

That's where the Deque (pronounced "deck," short for double-ended queue) from the Swift Collections package comes in. It gives us O(1) performance for insertions and removals at both the beginning and the end. I'm going to show you how to use one to build a "Recently Viewed" manager for a photo app.

Setting up the Recent-Items Buffer

Imagine we want to keep track of the last five photos a user has opened. Whenever they open a new photo, it goes to the front. If we exceed five, the oldest one drops off the back. I'll start by sketching out a basic manager.

import Collections

struct RecentPhotosManager {
    var recentIDs: Deque<String> = []
    let maxLimit = 5

    mutating func photoOpened(id: String) {
        // Remove the ID if it's already in the list to avoid duplicates
        if let index = recentIDs.firstIndex(of: id) {
            recentIDs.remove(at: index)
        }
        
        // Put the newest item at the front
        recentIDs.prepend(id)
        
        // Keep the list size in check
        if recentIDs.count > maxLimit {
            recentIDs.removeLast()
        }
    }
}

Notice I used prepend(_:). If this were a standard Array, I would have used insert(id, at: 0). In a Deque, prepend is nearly instantaneous regardless of whether you have 5 items or 500,000.

The "Array Habit" Trap

One thing that trips me up—and probably will trip you up too—is that Deque implements RandomAccessCollection. This means it looks and feels exactly like an array. You can use subscripts, map, filter, and for-in loops. Because it's so similar, it's easy to forget that it's a specialized structure.

I actually made a mistake when I first implemented this logic in a previous project. I tried to use popFirst() to clear the oldest item, thinking it worked like a queue. But wait—in a "Recently Viewed" list, the first item is the newest one. I accidentally deleted the photo the user just clicked on!

// MY MISTAKE:
if recentIDs.count > maxLimit {
    recentIDs.popFirst() // Oops! This removes the most recent item.
}

I had to catch that during testing. For this specific use case, the "oldest" item is at the end of the collection, so removeLast() or popLast() is the correct choice. It's a silly mistake, but it happens when you're switching your brain between "Queue" logic (First-In, First-Out) and "Stack" logic (Last-In, First-Out) while using a tool that supports both.

When to actually reach for a Deque

You might be wondering, "Why not just use a Deque for everything?" Well, Deque has a slightly different memory layout than Array. While it's incredibly efficient for ends-of-the-list operations, it can have a tiny bit more overhead for some other operations.

My rule of thumb: if your primary interaction pattern involves prepend or popFirst, use a Deque. If you're mostly appending to the end and iterating through the list, stick with Array. The Swift Collections package is a powerful addition, but it's a toolbox—pick the tool that fits the specific movement of your data.




📋 Practical Task

Build a Sliding-Window Log Buffer

Create a class called LogBuffer that stores the most recent 100 log messages. The buffer should have the following requirements:

  • Use a Deque<String> from the Swift Collections package to store the logs.
  • Implement a method addLog(_ message: String) that prepends the new message to the start of the buffer.
  • Ensure that the buffer never exceeds 100 items by removing the oldest messages from the back.
  • Implement a method getRecentLogs() that returns the logs as a standard Array<String> (hint: you can initialize an Array by passing the Deque into the Array's initializer).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.