What does the associated type mean in Swift 5+?

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

The associated type in Swift gives a placeholder name to a type that will be used as part of the protocol. When the protocol is conformed, the actual type to use for that it is specified. The associated type makes the protocol generic by providing a type placeholder.

I was very confused about the associated type at the beginning. I found that the best way to understand this concept is to use code example. For instance, I have created a protocol for the shopping cart. In the shopping cart, I can add, remove or count different type of shopping items. The type of shopping items will depend on which type of store I have created.

protocol ShoppingCartable {
    associatedtype ProductType

    var products: [ProductType] { get set}
    mutating func addToCart(_ product: ProductType)
    mutating func removeFromCart(_ product: ProductType)
    func totalProducts() -> Int
}

// Let's provide default behaviour of the function by
// protocol extension
extension ShoppingCartable {
    mutating func addToCart(_ product: ProductType) {
        products.append(product)
    }

    mutating func removeFromCart(_ product: ProductType) {
        // ...
    }

    func totalProducts() -> Int {
        return products.count
    }
}

Now, I have created two structs. The first one is the Food struct which will be used for the associated type. The second one is FoodStore which will conform to our ShoppingCartable protocol. Here, the Swift compiler uses Food type to fill the placeholder in the associated type. However, Food is a very simple type but we can also use a type alias in case of complicated types.

struct Food {
    let name: String
    let price: Double
}

struct FoodStore: ShoppingCartable {
    var products: [Food] = []
}

var store = FoodStore()
let milk = Food(name: "Milk", price: 5.0)
store.addToCart(milk)


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.