Understand associatedtype in Swift easy
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 = IntYES, 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 -> MoneyCreate 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 !
