Skip to Content
Course content

112: Type Erasure with AnyObject and any

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 Protocol when you want a collection of different types (structs, enums, classes) that all share a behavior.
  • Use AnyObject when 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 Device with a method checkStatus() that prints a message.
  • Create a HighEndCamera class that conforms to Device.
  • Create a BasicMicrophone struct that conforms to Device.
  • 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.