Swift Associate Type

To get to know Swift's Associated Type, we need to know the Protocol of the Swift basically. Associated Type helps you to use the protocol generically. It serves as a placeholder for types used in Protocol.

To know about Protocol before learning about Associated Type in Swift, you can have a look at the Swift official document about it. Swift.org is now open sourced in Github and is one of the really well documented site I have ever seen.


protocol ItemStoring {
    associatedtype DataType

    var items: [DataType] { get set }
    mutating func add(item: DataType)

Let's start with the ItemStoring protocol as an example, where DataType is Associated Type. The items and add functions are using this.


extension ItemStoring {
    mutating func add(item: DataType) {

You can also use DataType to have a default implementation of the add function in your extension.


struct NameDatabase: ItemStoring {
    var items = [String]()

You can now see the advantages of Associated Type. I made a struct that conforms to the ItemStoring protocol. If you just write something like this Swift knows that the DataType is String, and your code works accordingly.