Join Károly Nyisztor for an in-depth discussion in this video Constrained associated types, part of Swift 4: Protocol-Oriented Programming.
- [Narrator] We can also define a generic type that adopts the anyrepresentable protocol. I'm going to create a structure called GenericTagged. This structure is going to be generic so let's provide the placeholder type as usual. And it conforms to Anyrepresentable. I add the missing properties, just copy and paste from our previous structure. And for the content type, I'm going to set the type to our T placeholder.
Now, we can provide the type when creating an instance of the structure. So, let's create a constant called TaggedDouble which is of type GenericTagged. And we can provide type which is Double between angled brackets and I'm going to initialize it with a tag called pi and assign it a value of Double dot pi.
It could even delete the type because Swift's type inference engine can figure out a type based on the value we provide. Now, we can also add type constraints to an associated type in the protocol. For example, we can restrict the content type to types that conform to equatable. Now, we must also enhance the generic tag structure called in it. I'm going to add the constraint constant here.
Finally, let's implement the is equal operator It's a static operator, static function. I must provide the left hand operator which is of type genericTagged. And the right hand side operand which is also GenericTagged. The result is, as we know, a Boolean. We consider two instances to be equal if their tags match and if their content is also the same.
So, let's return if left hand side's tag matches the right hand side's tag and the left hand side's content is equal to the right hand side's content. Generics are super useful. And Swift makes it easy for us to implement and use generic types and functions. We can also make our protocols work with placeholder tags. Protocol oriented programming wouldn't be as flexible and elegant without generics.
- Comparing object-oriented programming with protocol-oriented programming
- Methods and class-bound protocols
- Adopting a protocol
- Declaring asynchronous behavior
- Preparing and implementing fallback logic
- Implementing an app using protocol-oriented programming