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
112: Type Erasure with AnyObject and any
I've noticed a recurring pattern when developers start diving into advanced Swift types: they treat AnyObject and any Protocol as interchangeable synonyms for "I don't care what the specific type is." It's a logical leap to make, but it's one that will eventually lead you into a wall of compiler errors—especially when you start mixing classes and structs.
The Myth that AnyObject and 'any' are Interchangable
A common misconception is that AnyObject is simply the "generic" version of any protocol. You might think that if you have a protocol and you want to store a list of objects that conform to it, AnyObject is the tool for the job. Let's look at why that's wrong concretely.
protocol Playable {
func play()
}
struct LocalTrack: Playable {
func play() { print("Playing local file...") }
}
class StreamingTrack: Playable {
func play() { print("Streaming from cloud...") }
}
// This will fail to compile
let playlist: [AnyObject] = [StreamingTrack(), LocalTrack()]
The compiler will scream at you here. Why? Because LocalTrack is a struct. AnyObject isn't a general "anything" type; it is specifically a protocol that is only conformable by classes. When you use AnyObject, you are telling Swift: "I promise this is a reference type." By trying to put a struct in there, you've broken that promise.
Wrapping Types in Existential Containers
This is where any comes in. When you write any Playable, you aren't just pointing to an object; you are creating what we call an "existential container."
Think of it as a box. The box has a label that says "Playable." Inside the box, Swift hides the actual concrete type (whether it's a LocalTrack struct or a StreamingTrack class) and only exposes the methods defined in the Playable protocol. This is the essence of type erasure: we are "erasing" the specific identity of the type and keeping only the behavior we care about.
// This works perfectly
let playlist: [any Playable] = [StreamingTrack(), LocalTrack()]
for track in playlist {
track.play() // Swift opens the box and calls the method
}
I like to think of any as a way of saying, "I don't know what this is, and I don't want to know, as long as it can do these specific things." It's incredibly powerful for building plugin architectures or heterogeneous lists where the underlying data structures vary wildly.
Choosing Between Class-Only and Type-Agnostic Erasure
So, if any is so flexible, why does AnyObject even exist? Because sometimes, you need the guarantees of a reference type. For example, if you are dealing with delegates or memory management (like weak references), you cannot use any because a struct cannot be held weakly.
If your protocol is marked as class-only (by inheriting from AnyObject), you are explicitly telling the compiler that this protocol should never be implemented by a struct. In that specific scenario, any MyClassProtocol and AnyObject overlap in utility, but they serve different architectural purposes.
- Use
any Protocolwhen you want a collection of different types (structs, enums, classes) that all share a behavior. - Use
AnyObjectwhen you are specifically interacting with the Objective-C runtime or need to ensure that the type is a reference type for memory management reasons.
Just be careful: overusing any can lead to a performance hit because of the overhead of that "box" (the existential container). If you know the type won't change during the lifetime of a variable, you're usually better off using generics or the some keyword, but we'll tackle the nuances of that in a later lesson.
📋 Practical Task
Implementing a Multimedia Device Registry
You are building a system to manage various hardware peripherals. Some peripherals are complex classes (like a HighEndCamera) because they manage a persistent connection to hardware, while others are simple structs (like a BasicMicrophone) that just hold configuration data.
Your Goal: Create a registry that can store and trigger a "status check" on any device, regardless of whether it is a class or a struct.
- Define a protocol
Devicewith a methodcheckStatus()that prints a message. - Create a
HighEndCameraclass that conforms toDevice. - Create a
BasicMicrophonestruct that conforms toDevice. - Create an array called
connectedDevices. Use the correct type erasure keyword to ensure this array can hold both the camera and the microphone. - Iterate through the array and call
checkStatus()on each device.
Constraint: Do not use AnyObject for the array, as it will cause the BasicMicrophone struct to fail the type check.
There are no comments for now.