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
177: Timer for Scheduled Execution
Let's imagine we're building a simple text editor. One feature I always want in these kinds of apps is an "Auto-save" indicator. You know the one—a little piece of text in the corner that says "Saving..." every few seconds so the user doesn't panic about their work.
Just making it tick
My first instinct is to just trigger a function every few seconds. In Swift, the go-to for this is Timer. I'll start with the most straightforward approach: scheduledTimer. I'll write a quick class to handle the saving logic and see if I can get it to fire.
class DocumentManager {
func startAutoSave() {
Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in
print("Auto-saving document at \(Date())...")
}
}
}
let manager = DocumentManager()
manager.startAutoSave()
If I run this in a playground or a long-running app, it works exactly as expected. Every three seconds, I see that print statement. Easy, right? But here is where things usually go sideways in a real project.
The "Zombie" Timer
I noticed something annoying during testing. If I destroy the DocumentManager instance—maybe the user closes the document—the timer keeps firing. I can still see "Auto-saving..." in my console even though the object that started it is long gone. This is a classic leak. Because Timer.scheduledTimer adds the timer to the current run loop, the run loop holds a strong reference to the timer, and the timer holds a strong reference to the closure.
I need a way to kill the timer manually. To do that, I can't just call the method in a vacuum; I need to keep a reference to the timer object itself.
class DocumentManager { var saveTimer: Timer? func startAutoSave() { // I'll store the timer in my optional property saveTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in print("Auto-saving...") } } func stopAutoSave() { saveTimer?.invalidate() saveTimer = nil print("Timer stopped.") } }Now, by calling
invalidate(), I'm telling the run loop to let go of the timer. This is non-negotiable for any timer you create; if you don't invalidate it, you're basically leaving a light on in a room you've already left.The Memory Trap
There's one more thing. As I'm refining this, I realize that if my closure starts touching properties inside
DocumentManager(like adocumentContentstring), I'm creating a strong reference cycle. The timer owns the closure, and the closure ownsself(the DocumentManager). Even if I callstopAutoSave, if I forgot to do it in adeinit, the object might never actually be destroyed.I'll fix this by using a
weak selfcapture list. It's a habit I've developed over the years—whenever you see a timer closure, immediately ask yourself: "Who owns whom?"class DocumentManager { var saveTimer: Timer? var documentName = "MyNotes.txt" func startAutoSave() { saveTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { [weak self] timer in // Now 'self' is optional. If the manager is gone, this block does nothing. guard let self = self else { return } print("Auto-saving \(self.documentName)...") } } deinit { saveTimer?.invalidate() } }Now it's clean. The timer is scheduled, it's reference-tracked so it can be stopped, and it doesn't hold the manager hostage in memory. It's a simple pattern, but missing any one of these steps usually leads to a bug that's a nightmare to track down in a large codebase.
📋 Practical Task
Build a Pomodoro Countdown Trigger
Create a class called PomodoroTimer that simulates a focus session. The class should meet the following requirements:
- Maintain a
secondsRemaininginteger property (start it at 25 minutes, or 1500 seconds for testing). - Implement a
startSession()method that uses aTimerto decrementsecondsRemainingby 1 every second. - The timer must use
[weak self]to avoid memory leaks. - Implement a
stopSession()method that invalidates the timer. - The timer should automatically call
stopSession()and print "Time is up!" whensecondsRemainingreaches 0.
There are no comments for now.