Generics in Swift — Part 2
Before starting this article I suggest you to check Part 1 of Generic.
In this article we will learn how to use generic in protocol. If we have to use a generic type in protocol, we can define that as associatedtype. I will keep this as simple as possible by giving some examples. Let’s look at code below:
In above example we define ID as associated type, it helps us to define generic datatype in protocol. ID will be converted to actual data-type based on class which confirms to protocol. See example below:
In above example we did following tasks:
1. Created new protocol PersonProtocol, which have property name and age.
2. Confirm struct with PersonProtocol which again confirm to Identifiable protocol.
3. Override method identifier() and define return type as String.
Above code will automatically consider that ID will be replaced by String. This is very basic example to use associatedType.
Where clause:
Where clause is used to restrict datatype of ID object, for example if we define a class which accept generic type which confirm to PersonProtocol but ID is acceptable only as String. In this case we can use Where clause in following manner:
In above code we just restricted that ID should be of type String. So let say you define person class in following manner:
and now create object of Car in following way:
var obj = Car<Person>()
Above line of code will give error ‘Car’ requires the types ‘Int’ and ‘String’ be equivalent.
Above error come because identifier() function in Person return Int and Car is expecting datatype where identifier() return String.
I have shared very good example of generic use in Part 3 of my series.