Override Protocol Associated Type
Introduction
Welcome to Lesson 3 of Generic Protocols. Nice and easy. You will learn multiples way to override pre-defined associated type.
Problem
How to override typed-defined protocol?
Design Protocol
Create a protocol called, FamilyProtocol. It has an associatedtype called familyType in Int.
1. protocol FamilyProtocol {
2. associatedtype familyType = Int
3. var familyMembers: [familyType] { get set }
4. }
Design Struct
Create a struct that conforms to FamilyProtocol.
1. struct NumberFamily: FamilyProtocol {
2. var familyMembers: [Int] = [1, 2, 3]
3. }
5. let numberFam = NumberFamily() // familyType == Int
Override Associated Type Directly
You may override familyType by creating a typealias in String or any other types.
1. struct NormalFamily: FamilyProtocol {
2. typealias familyType = String
3. var familyMembers: = ["Bob", "Bobby"]
4. }
5. }
You don’t even need to create a typealias. familyType can be modified based on the value.
1. struct NormalFamily: FamilyProtocol {
2. var familyMembers: = ["Bob", "Bobby"]
3. }
4. }
Override Associated Type With Generic Struct
Create a generic struct with a type T. The struct conforms to FamilyProtocol.
1. struct LeeFamily<T>: FamilyProtocol {
2. var familyMembers: [T] = []
3. }
1. let family = LeeFamily(familyMembers: ["Bob", "Bobby", "Lee"])
Process
TbecomesStringbased on["Bob", "Bobby", "Lee"]familyTypebecomesStringbased onT
Source Code
Resources
Generic Protocols with Associated Type
Conclusion
You’ve learned how to override pre-defined associated types in protocols. Yet, it’s ironic that you set the type as defined within protocols because it goes against the meaning of generics. Just don’t do it.
In the following lesson, you will discover that Protocol Oriented Programming is not the ultimate savior in all cases.
Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.
