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
123: Implementing a Hash Table in Swift
You've spent plenty of time using Swift's built-in Dictionary, but under the hood, that's just a highly optimized hash table. If you're prepping for a technical interview or just want to understand why lookups are O(1), you need to know how to build one from scratch. I find the best way to wrap your head around this is by building a simple inventory system for a vintage record store.
How do I actually turn a key into an array index?
The core of a hash table is the hash function. In Swift, we don't have to write the math for the hash itself because the Hashable protocol does the heavy lifting for us. Any type that conforms to Hashable has a hashValue property.
The trick is that the hashValue is a massive integer, but your underlying storage is just a fixed-size array (the "buckets"). To map that huge number to a valid index, we use the modulo operator. Here is the basic setup for our record store:
struct Record: Hashable {
let artist: String
let album: String
}
class RecordStoreHashTable<Key: Hashable, Value> {
private var buckets: [[(Key, Value)]]
private var count = 0
private let capacity = 10
init() {
// Initialize an array of 10 empty arrays (buckets)
self.buckets = Array(repeating: [], count: capacity)
}
private func index(for key: Key) -> Int {
// Use abs() because hashValue can be negative
return abs(key.hashValue) % capacity
}
}
What's the best way to deal with collisions?
Eventually, two different keys will hash to the same index. It's mathematically inevitable. I usually recommend "Separate Chaining" for custom implementations because it's the most intuitive. Instead of storing a single value at each index, we store an array of tuples—essentially a little list of all items that collided at that spot.
When you put a value, you find the bucket, check if the key already exists to update it, or just append a new tuple if it doesn't. When you get a value, you jump to the bucket and do a linear search through that small list.
func put(key: Key, value: Value) {
let idx = index(for: key)
// Check if the key already exists in the bucket to update it
for i in 0.. Value? {
let idx = index(for: key)
// Search the specific bucket for our key
return buckets[idx].first(where: { $0.0 == key })?.1
}
How do I keep the performance fast as the table fills up?
If you have 1,000 records but only 10 buckets, your "O(1)" lookup quickly turns into O(n) because your buckets become long lists. To fix this, we use a "Load Factor"—usually around 0.75. Once the number of elements divided by the capacity exceeds this threshold, we need to resize.
You can't just copy the array to a bigger one; you have to re-hash every single element. Because the capacity changed, the result of hashValue % capacity changes, meaning every item might move to a completely different bucket.
I'll be honest: implementing a dynamic resize is where most people get tripped up. You essentially create a brand new, larger RecordStoreHashTable and migrate all the existing tuples into it. If you don't resize, your hash table is basically just a collection of slow arrays.
📋 Practical Task
Build a Movie Metadata Cache
Implement a custom hash table to act as a cache for movie metadata. Your implementation must meet the following requirements:
- Create a
Moviestruct that conforms toHashable(usetitleandreleaseYearas the properties). - Implement a
MovieCacheclass with a fixed capacity of 15 buckets. - Implement a
set(movie:value:)method that handles collisions using separate chaining. - Implement a
getValue(for movie:)method that returns the cached metadata (aString) ornilif not found. - Implement a
remove(movie:)method that deletes the entry from the bucket if it exists.
Test your cache by adding three different movies that you suspect might collide (or just add a variety of movies) and ensure you can retrieve and delete them correctly.
There are no comments for now.