Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
181: Deque from Swift Collections Package
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 standardArray<String>(hint: you can initialize an Array by passing the Deque into the Array's initializer).
There are no comments for now.