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
111: where Clauses in Generic Constraints
I've noticed a recurring pattern when developers first hit generic constraints in Swift: they treat the angle brackets <T: SomeProtocol> as the only place where constraints live. They assume that if they can't fit a requirement inside those brackets, the logic is either impossible or requires a complete architectural rewrite.
Thinking the angle brackets can handle everything
Here is the misconception in action. Imagine you're building a system to handle different types of DataStore objects. You have a protocol with an associated type, and you want to write a function that only works if the store's items are Codable so you can save them to disk.
protocol DataStore {
associatedtype Item
var items: [Item] { get }
}
// This will NOT compile
func backupStore<S: DataStore where S.Item: Codable>(store: S) {
// Swift doesn't let you put 'where' inside the angle brackets
}
If you try to cram the where clause inside the < >, the compiler will throw a fit. You might think, "Wait, I'm just constraining the type, why can't I do it here?" The reason is that angle brackets are for type inheritance (T is a subtype of X), but they aren't designed to handle type relationships or associated type constraints.
Using where to reach inside associated types
The where clause is your escape hatch. It allows you to define constraints that are too complex for the shorthand syntax. By moving the constraint after the function signature, you can "reach inside" the generic type S and place a requirement on its associated type Item.
func backupStore<S: DataStore>(store: S) where S.Item: Codable {
print("Backing up items...")
// Now we can safely use JSONEncoder because we know S.Item is Codable
}
I like to think of the angle brackets as the "broad strokes" (S must be a DataStore) and the where clause as the "fine print" (specifically, the Item inside that DataStore must be Codable). This separation makes the code much easier to read once you get used to it.
Constraining the relationship between two generic types
The real power of where shows up when you have two different generic types and you need them to be the same, or have a specific relationship. You can't do this in the angle brackets at all.
Let's say you're writing a merge function for two different collections. You don't just want them to be sequences; you want to ensure that the elements of the first collection are the exact same type as the elements of the second.
func mergeCollections<T, U>(_ first: T, _ second: U) where T.Element == U.Element {
// This function only exists if T and U share the same Element type
}
Without the where clause, you'd be forced to use Any or perform dangerous type casting inside the function body. By using where T.Element == U.Element, you move the requirement to the compiler. If a developer tries to merge a list of Integers with a list of Strings, the code won't even compile. I'd much rather have a compiler error today than a crash in production tomorrow.
📋 Practical Task
Implementing a Type-Safe API Response Validator
You are building a networking layer where different API responses are handled by different ResponseHandler objects. Some handlers deal with raw data, while others deal with structured JSON.
Your Task:
- Create a protocol called
ResponseHandlerwith anassociatedtype Payload. - Create a struct called
JSONPayloadthat conforms toCodable. - Create a struct called
UserHandlerthat conforms toResponseHandler, usingJSONPayloadas itsPayload. - Implement a generic function called
validateAndProcess. This function should take ahandlerof typeH(whereHis aResponseHandler), but it must only be callable if thePayloadof that handler conforms toCodable. - Inside the function, print "Processing codable payload...".
Ensure you use a where clause to constrain the associated type of the protocol, rather than trying to constrain the handler itself to a specific concrete class.
There are no comments for now.