Member-only story

Swift Programming Tutorial: Associated Types

Understand Associated Types in a Few Minutes

Arc Sosangyo
3 min readDec 3, 2024
Photo by Daniel McCullough on Unsplash

This article is part of my Swift Programming Tutorial series.

Okay, so you’ve heard of protocols, right? Protocols are like contracts for your code. You say, “Hey, I promise to provide these functions and properties if I conform to this protocol,” and Swift says, “Cool, I trust you.” But what happens when your protocol wants to work with any type of data? That’s where associated types ride in on their shining steeds.

An associated type is a placeholder type in a protocol. It’s like saying, “I’m not sure what type you’ll use here, so I’ll leave a blank and let you fill it in later.” This makes your protocol super flexible and reusable without committing to a specific type up front.

Now you may ask: Why not just use Any?

Good question! Using Any would work for generic scenarios, but it’s like trying to hold water in a strainer—Any has no type information. You’d constantly have to check and cast your types. With associated types, Swift ensures your types are correct at compile time, so you don’t end up with a runtime surprise party (and not the good kind).

Let’s say you want to create a protocol for a container that can hold stuff. Any kind of stuff. Enter the hero…

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.

Responses (1)