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
242: Debugging Data Races with Thread Sanitizer
A few years ago, I worked with a developer who spent nearly an entire week chasing a bug that only appeared on a physical iPhone 13, but never in the Xcode simulator. He was building a custom image caching system, and every few hundred requests, the app would just... vanish. No helpful crash log, just a SIGABRT or a random memory corruption error. He spent days auditing his logic, convinced there was some obscure edge case in the API response. The reality? He was writing to a Dictionary on a background thread while simultaneously reading from it on the main thread to update the UI. It was a classic data race, the kind of "Heisenbug" that disappears the moment you try to look at it with a debugger.
A data race happens when two or more threads access the same memory location concurrently, and at least one of those accesses is a write. In Swift, this is a recipe for disaster because many of our standard collections aren't thread-safe. The scary part is that your code might work perfectly for months, then crash in production the moment a user's device has enough CPU cores to actually run those operations at the exact same millisecond. This is where the Thread Sanitizer (TSan) comes in. It's not a static analyzer that looks at your code; it's a runtime tool that monitors memory access and screams the moment it sees a conflict.
Turning on the Watchdog
You won't find TSan running by default because it carries a heavy performance cost—your app will run significantly slower and consume more memory. But during the debugging phase, that's a trade-off you have to make. To get it running, you need to dive into your project's Scheme settings. Click on your target name next to the Run button in the top toolbar, select Edit Scheme..., and head over to the Diagnostics tab. There, you'll see a checkbox for Thread Sanitizer.
Once you check that box and run your app, Xcode starts tracking every single memory access. I usually recommend running your app through its "stress paths"—the parts of the UI where you're triggering lots of network requests or heavy data processing—because that's where the races are most likely to hide.
Decoding the TSan Report
When TSan catches a race, it doesn't just crash the app; it pauses execution and prints a detailed report in the console. At first glance, it looks like a wall of text, but you only need to look for two specific things: the Write and the Previous Read (or vice versa).
Thread 2: Write of size 8 at 0x600001234560 by thread T2
Thread 1: Previous read of size 8 at 0x600001234560 by thread T1
The magic is in the stack traces provided immediately below these lines. TSan tells you exactly which line of code performed the write and which line performed the read. If you see your ImageCache.save() method appearing in the "Write" trace and ImageCache.fetch() appearing in the "Read" trace, you've found your culprit. I've found that the most common mistake is thinking a DispatchQueue.main.async call "protects" the data; it only protects the UI update, not the underlying data structure you're accessing inside that block.
Eliminating the Race
Once you've identified the conflict, you have to synchronize the access. Since we've already moved past the basics of concurrency in this course, you know that the modern Swift way to handle this is using an actor. By moving your shared state—like that problematic Dictionary—into an actor, Swift guarantees that only one task can access that state at a time, effectively turning the "race" into a "queue."
If you're working in a legacy codebase where actors aren't an option, you can use a concurrent DispatchQueue with a barrier flag for writes. This allows multiple simultaneous reads but ensures that when a write happens, it has exclusive access to the memory. Personally, I always push for actors now; they turn these runtime crashes into compile-time errors, which is a much friendlier way to spend your Tuesday afternoon.
📋 Practical Task
Fixing the Concurrent User Session Race
You have been handed a SessionManager class that is causing intermittent crashes in a production app. The manager tracks active user sessions in a dictionary, but it's being accessed from multiple background threads during a sync process.
class SessionManager {
var activeSessions: [String: Date] = [:]
func updateSession(userId: String) {
// This is called from various background threads
activeSessions[userId] = Date()
}
func getSession(userId: String) -> Date? {
// This is called from the main thread for UI updates
return activeSessions[userId]
}
}
// Simulation of the race
let manager = SessionManager()
for i in 0...1000 {
DispatchQueue.global().async {
manager.updateSession(userId: "user_\(i % 10)")
}
DispatchQueue.main.async {
_ = manager.getSession(userId: "user_\(i % 10)")
}
}
Your Task:
- Create a new Xcode project and paste the code above into a command-line tool or a simple View Controller.
- Enable the Thread Sanitizer in the Scheme Diagnostics.
- Run the app and observe the TSan warning in the console. Identify the exact lines causing the conflict.
- Refactor the
SessionManagerinto anactorto resolve the data race. - Update the simulation code to use
awaitwhen callingupdateSessionandgetSession. - Run the app again with TSan enabled to verify that the data race is gone.
There are no comments for now.