Understand associatedtype in Swift easy

Felix Schmidt
Nov 6 · 2 min read
Photo by Allef Vinicius on Unsplash

associatedtype helps you to make protocols more generic. It’s not hard to understand when you just read my little example below.

Just imagine you have a wallet for money. Money kinds can be coins or banknotes. But sometimes you have special wallets that are more suitable for coins, because they provide not enough space for banknotes. Or you have a flat leather wallet for rich people that only fits banknotes.
One thing both wallet types have in common: they’ve money inside of it!

Money could be our associatedtype!

So, let’s define a wallet protocol:

protocol WalletProtocol {
associatedtype Money

var compartment: [Money] { get set }

mutating func add(money: Money)
}

You see there is declared an associatedtype of type Money. Money will be collect in a compartment. At the moment it doesn’t matter what kind of money (coins, banknotes), you know the wallet can hold money. And also it doesn’t matter how to add the money, thats why let us just add a default implementation of add(money:) .

extension WalletProtocol {
mutating func add(money: Money) {
compartment.append(money)
}
}

Okay. We know we have two kinds of money: coins and banknotes. Let’s define an alias:

typealias Coin = Float
typealias Banknote = Int

YES, I know, here we could better use an enum for that stuff, but I want to explain associatedtype!

Now it comes the magic. Let us make two wallets, one for coins, one for banknotes. Both implements the wallet protocol.

struct CoinWallet: WalletProtocol {
var compartment = [Coin]()
}
struct BanknoteWallet: WalletProtocol {
var compartment = [Banknote]()
}

You can see, Swift maps the data type of compartment to our associated type.

Coin -> Money
Banknote -> Money

Create a wallet of every kind:

var coinWallet = CoinWallet(), banknoteWallet = BanknoteWallet()// only Coin/Float values can be added
coinWallet.add(money: 0.5)
// only Banknote/Int values can be added
banknoteWallet.add(money: 20)

That’s it, associatedtype !

Felix Schmidt

Written by

senior  iOS & web app developer @ t-systems mulimedia solutions in dresden, germany.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade