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
From the course: Swift 5: Protocol-Oriented Programming
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
(Locked)
The importance of generics3m 12s
-
(Locked)
Defining generic functions and methods3m 32s
-
(Locked)
Working with generic types3m 29s
-
(Locked)
Placeholder types in protocols1m 54s
-
(Locked)
Using generics with protocols1m 45s
-
(Locked)
Challenge: Implementing a generic stack1m 21s
-
(Locked)
Solution: Implementing a generic stack6m 45s
-
(Locked)
-
-