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
186: Primary Associated Types
If you've been working with protocols and associated types for a while, you know the "associated type" headache. For years, once we added an associatedtype to a protocol, that protocol stopped being a simple type we could pass around. We had to deal with some and any, or write those massive where clauses that make your code look more like a math textbook than a program.
Swift 5.7 introduced Primary Associated Types, and honestly, it's one of those changes that makes me wonder why we ever did it the hard way. It allows us to treat a protocol with associated types almost like a generic class or struct.
The struggle with generic protocols
Let's build a simple DataStore. I want a protocol that can save and retrieve a specific type of data, whether that's saved to a database, a file, or just held in memory for testing.
protocol DataStore {
associatedtype Item
func save(_ item: Item)
func fetch() -> Item?
}
Now, here is where I usually run into a wall. I want to write a SyncManager that takes a DataStore and pushes data to it. In the past, I might have tried this:
class SyncManager {
func performSync(store: any DataStore, item: String) {
store.save(item) // ❌ Compiler Error!
}
}
I'll admit, I still do this by reflex sometimes. The compiler screams at me because any DataStore is an existential type. It knows it's some kind of store, but it has no idea if the Item it expects is a String, an Int, or a User object. The types don't line up.
Cleaning things up with Primary Associated Types
To fix this, we can promote the associated type to a Primary Associated Type. We do this by adding the type in angle brackets right next to the protocol name. It looks like a generic, but it's actually just telling Swift: "This is the main type I'll be using to identify this protocol."
protocol DataStore<Item> {
associatedtype Item
func save(_ item: Item)
func fetch() -> Item?
}
Notice that we still keep the associatedtype Item inside the body. The <Item> on the protocol declaration is just a "hint" for the type system. Now, look at how much cleaner our SyncManager becomes. We can specify exactly what kind of store we want using any DataStore<String>.
class SyncManager {
func performSync(store: any DataStore<String>, item: String) {
store.save(item) // ✅ This now works perfectly
}
}
I love this because it removes the ambiguity. We aren't just saying "any store"; we're saying "any store that specifically handles Strings."
Applying this to real implementations
To make this concrete, let's implement a couple of different stores. The implementation side doesn't actually change—we still just define the Item type as we always have.
struct MemoryStore: DataStore {
typealias Item = String
private var storage: String?
func save(_ item: String) {
storage = item
}
func fetch() -> String? {
return storage
}
}
struct FileStore: DataStore {
typealias Item = String
func save(_ item: String) {
print("Saving \(item) to disk...")
}
func fetch() -> String? {
return "Data from disk"
}
}
Now we can swap these out effortlessly. Since both conform to DataStore<String>, the SyncManager doesn't care which one it gets.
let manager = SyncManager()
let memStore = MemoryStore()
let fileStore = FileStore()
manager.performSync(store: memStore, item: "Hello Memory!")
manager.performSync(store: fileStore, item: "Hello Disk!")
By using Primary Associated Types, we've turned a clumsy protocol into a first-class generic citizen. You get the flexibility of protocols with the type safety of generics, without the syntactic noise of the old where clauses.
📋 Practical Task
Implementing a Generic Notification Dispatcher
You are building a notification system. You need a protocol called NotificationHandler that can handle a specific type of Payload.
Your task:
- Define the
NotificationHandlerprotocol using a Primary Associated Type for thePayload. It should have one method:func handle(payload: Payload). - Create a struct called
EmailHandlerthat conforms toNotificationHandlerwhere thePayloadis aString. - Create a struct called
AlertHandlerthat conforms toNotificationHandlerwhere thePayloadis anInt(representing an error code). - Write a function called
dispatchNotificationthat takes two arguments: a handler (using theanykeyword and the primary associated type) and a payload of the matching type. - Call this function twice: once with the
EmailHandlerand a string, and once with theAlertHandlerand an integer.
There are no comments for now.