Associated Types in iOS Swift

Chanakya Hirpara
2 min readJun 1, 2023

Associated Types in Swift provide a way to define placeholder types within protocols. They allow you to specify that a protocol must provide a type, without specifying the actual type itself. Associated Types are particularly useful when you want to define protocols that can work with different types of associated data. In this post, we'll explore Associated Types in iOS Swift with a real-time example to showcase their usage.

Understanding Associated Types

Associated Types allow you to define a placeholder type within a protocol declaration. They act as placeholders for the actual types that conforming types will provide. Associated Types provide a level of abstraction, allowing you to define generic protocols without committing to specific types.

Associated Types are declared using the associatedtype keyword within the protocol declaration. The actual type that conforms to the associated type is determined by the conforming types.

Real-time Example: DataSource Protocol

Let's consider a real-time example of creating a DataSource protocol using associated types. We'll define a protocol that represents a data source for a table view, where the specific type of data is determined by the conforming type.

protocol DataSource {
associatedtype DataType

func numberOfItems() -> Int
func item(at: Int) -> DataType
}

class MyDataSource: DataSource {
typealias DataType = String
private var items: [String] = ["Apple", "Banana", "Orange"]

func numberOfItems() -> Int {
return items.count
}

func item(at: Int) -> DataType {
return items[at]
}
}

let dataSource = MyDataSource()
print(dataSource.numberOfItems()) // Output: 3
print(dataSource.item(at: 1)) // Output: "Banana"

In this example, we define a DataSource protocol with an associated type called DataType. The protocol requires two methods: numberOfItems() to get the total number of items, and item(at:) to retrieve an item at a specific index.

The conforming type, MyDataSource, specifies the associated type DataType as String. It provides an implementation for the required methods and maintains an internal array of strings as the data source.

We create an instance of MyDataSource called dataSource and use it to retrieve the number of items and an item at a specific index. The associated type DataType is inferred as String in this case.

Associated Types enable us to create generic protocols that can be used with different types of data sources. The specific type is determined by the conforming type, allowing for flexibility and reusability.

It's important to note that multiple associated types can be declared within a single protocol, providing even more flexibility when defining generic protocols.

I hope this example helps you understand Associated Types in iOS Swift and how they can be used to create generic protocols with placeholder types!

Please clap, share and follow for more.

--

--