Intro to Protocol Associated Type

Introduction

Welcome to the first lesson of Generic Protocols. In Chapter 4, Protocol Oriented Swift, you’ve mastered how to set protocol requirements. In this chapter, you will learn how to set the requirements generic, providing freedom and scalability.

Problem

How to create generic protocols

#1 Rule: Type must be defined before compiled.

Design Generic Struct - Review

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

  1. struct GenericStruct<T> {
  2. var property: T?
  3. }

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 Normal Protocol

To appreciate generic protocols, let’s go back to your past. Design a protocol that has one property requirement whose name is property in String.

  1. protocol NormalProtocol {
  2. var property: String { get set }
  3. }

Design Class

Create a class called, NormalClass that conforms to NormalProtocol.

  1. class NormalClass: NormalProtocol {
  2. var property: String = "Bob"
  3. }

property 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.

  1. protocol GenericProtocol {
  2. associatedtype myType
  3. var anyProperty: myType { get set }
  4. }

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

Define Associated Type

Create a struct called, SomeStruct and conforms to GenericProtocol. As the requirement, anyProperty must be present. However, you may implicitly define the type of myType based on the value you assign to anyProperty.

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

Define Associated Type with Typealias

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

  1. struct ExplicitStruct: GenericProtocol {
  2. typealias myType = Bool
  3. var anyProperty = true
  4. }

Source Code

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.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.