From the course: Swift 5: Protocol-Oriented Programming

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Using generics with protocols

Using generics with protocols

From the course: Swift 5: Protocol-Oriented Programming

Start my 1-month free trial

Using generics with protocols

- [Instructor] We can adopt protocols in generic types too. Let's create a generic structure called GenericTagged. I provide the placeholder type and make it adopt the Taggable protocol. We can provide that type when creating an instance of this generic structure. So let's create a constant called taggedDouble. I've typed GenericTagged, and I provide the type, which is double, between angle brackets. And let's initialize it with a tag called pi, and the value Double.pi for the data. We could even delete the type, because Swift's type inference engine can figure it out without our help. I'm going to remove the type, and it should combine just fine. We can also add type and strength to an associated type in the protocol. For example, we can restrict the data property to types that conform to Equatable. Now, after this change, we need to update the generic tag structure as well. And the placeholder type has to conform…

Contents