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
165: The Factory Pattern in Swift
You've probably encountered situations where your code is littered with switch statements or if-else blocks just to decide which class to instantiate. It usually happens when you have a few different versions of the "same" thing, and the logic to decide which one to use starts leaking into your view controllers or business logic. That's exactly where the Factory Pattern saves your sanity.
I want to show you how to handle this using a payment processing system. Imagine we support Credit Cards, PayPal, and Apple Pay. Each has its own unique setup, but from the perspective of our checkout screen, they all just need to "process a payment."
Defining a common interface
First, we need a contract. We don't want our app to care if it's talking to a PayPal API or a Stripe SDK; we just want to call a method and have the money move. I'll start by defining a simple protocol.
protocol PaymentMethod {
func processPayment(amount: Double)
}
class CreditCardPayment: PaymentMethod {
func processPayment(amount: Double) {
print("Processing $\(amount) via Credit Card...")
}
}
class PayPalPayment: PaymentMethod {
func processPayment(amount: Double) {
print("Redirecting to PayPal for $\(amount)...")
}
}
class ApplePayPayment: PaymentMethod {
func processPayment(amount: Double) {
print("Authenticating Apple Pay for $\(amount)...")
}
}
The mistake: Creating objects in the UI layer
When I first built a system like this years ago, I did the "obvious" thing. I put the instantiation logic right in the checkout function. It looked like this:
func completePurchase(amount: Double, method: String) {
let paymentProcessor: PaymentMethod
if method == "credit_card" {
paymentProcessor = CreditCardPayment()
} else if method == "paypal" {
paymentProcessor = PayPalPayment()
} else {
paymentProcessor = ApplePayPayment()
}
paymentProcessor.processPayment(amount: amount)
}
This works fine for three methods. But then the product manager asks for Google Pay, Klarna, and Bitcoin. Suddenly, my completePurchase function is 50 lines of instantiation logic. More importantly, if the CreditCardPayment class ever needs a new initializer argument (like an API key), I have to hunt down every single place in my UI code where I called CreditCardPayment() and update it. That's a recipe for bugs.
Centralizing creation with a Factory
To fix this, we move that "decision" logic into its own object. The Factory's only job is to look at the input and hand back the correct object. I like using an enum for the input because it prevents typos that happen with strings.
enum PaymentType {
case creditCard
case paypal
case applePay
}
class PaymentFactory {
static func makePaymentMethod(for type: PaymentType) -> PaymentMethod {
switch type {
case .creditCard:
return CreditCardPayment()
case .paypal:
return PayPalPayment()
case .applePay:
return ApplePayPayment()
}
}
}
Now, look at how much cleaner the checkout logic becomes. The UI doesn't know CreditCardPayment even exists; it only knows about the PaymentMethod protocol and the PaymentFactory.
func completePurchase(amount: Double, type: PaymentType) {
let processor = PaymentFactory.makePaymentMethod(for: type)
processor.processPayment(amount: amount)
}
Why this actually matters in the long run
You might think, "I just moved the switch statement to a different file. What did I actually gain?"
- Single Responsibility: The checkout function handles the purchase flow; the factory handles object creation.
- Decoupling: If I decide to replace
PayPalPaymentwith a newerPayPalV2Paymentclass, I only change one line in the factory. The rest of the app never even knows the class name changed. - Testability: I can now easily create a
MockPaymentclass for my unit tests and tell the factory to return that instead of hitting a real API.
📋 Practical Task
Build a Notification Dispatcher Factory
Your task is to implement a notification system that can send alerts via different channels: Email, SMS, and Push Notification.
- Create a protocol named
NotificationChannelwith a methodsend(message: String). - Create three concrete classes (
EmailChannel,SMSChannel, andPushChannel) that conform to this protocol and print a unique message for each. - Create a
NotificationTypeenum with cases for each channel. - Implement a
NotificationFactorywith a static method that takes aNotificationTypeand returns aNotificationChannel. - In your main code, simulate sending a message to a user by using the factory to instantiate the correct channel based on a variable, then calling the
send(message:)method.
There are no comments for now.