Associated type in Swift with Protocol?

Divesh Singh
1 min readOct 24, 2019

--

Associated types are a way to provide the run time data type holder inside the @protocol.

Suppose You have created a protocol that defines functions and properties with Any data -type. Now you can use that properties to implement the protocol.

You have a protocol that can defines array of String, so here you can define an array of associated type (instead of string).

Suppose I want to define Storage Strut using that protocol, and we don’t know what we will store in the database in the future. So here associated type will come to the picture.

See the below code for the example:

See the “nameDatabase” and “AgeDataBase”.

Where we can store string and Int using the same protocol. This is beauty of Associatetype.

--

--

Divesh Singh

Postgraduate from JEC Jabalpur || iOS and macOS developer, traveler |||| EM at Darwinbox | Ex-Samsung || Ex - Optimize IT Sys | Ex - R Systems