Browse Questions
- A Singleton ensures only one instance of a class exists globally.
- Protocol extensions let you add default implementations to protocol methods, so conforming types get behavior for free without inheriting from a base class.
- LLDB is the debugger built into Xcode.
- Breakpoints pause execution so you can inspect state.
Answer: A Singleton ensures only one instance of a class exists globally. It's convenient but widely overused in iOS.
Code Example:
// Standard Swift singleton
class AnalyticsManager {
static let shared = AnalyticsManager()
private init() {} // prevent external instantiation
func track(_ event: String) { ... }
}
// Usage
AnalyticsManager.shared.track("button_tapped")
Downsides:
- Hard to test — can't inject a mock; tests share global state
- Hidden dependencies — callers depend on it without declaring it
- Threading issues — shared mutable state needs synchronization
- Tight coupling — callers are coupled to the concrete type
When it's acceptable:
- Logging, analytics, app-level config (read-only)
- Avoid for anything that manages data or has side effects