Intro to Protocol Associated Type

    Problem

    How to create generic protocols

    Design Generic Struct - Review

    Create a generic struct that has one property whose name is .

    When you initialize, you may define T implicitly or explicitly.

    1. let explicitly = GenericStruct<Bool>()
    2. // T is Bool
    3. let implicitly = GenericStruct(property: "Bob")
    4. // T is String

    Design Class

    Create a class called, NormalClass that conforms to NormalProtocol.

    1. class NormalClass: NormalProtocol {
    2. }

    must be String. This ain’t free. There is an alternative.

    Introducing Generic Protocol

    When you design a protocol, you may add associatedtype which is analogous to typealias. Unlike typealias, the type is not defined.

    The type, myType, of anyProperty will be defined by either classes, structs, or enums.

    1. struct SomeSturct: GenericProtocol {
    2. }
    3. struct NewStruct: GenericProtocol {
    4. var anyProperty = "Bob" // myType = String

    Define Associated Type with Typealias

    As an alternative, you may define the type of myType explicitly by creating typealias.

    6001_intro_associated_type.playground

    Conclusion

    You’ve learned how to create generic protocols by implementing associatedtype. Like generic structs, the type of associatedType must be defined by the structs, classes, or enums that conform to the protocol. There are two ways to specify the type of associatedType. You may implicitly define it based on the value you assign. Second, or you may explicitly create a typealias that define the type upfront.

    In the following lesson, you will learn how to add limitation/constraints to protocol extension like generic constraints.