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.
let explicitly = GenericStruct<Bool>()
// T is Bool
let implicitly = GenericStruct(property: "Bob")
// T is String
Design Class
Create a class called, NormalClass
that conforms to NormalProtocol
.
class NormalClass: NormalProtocol {
}
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.
struct SomeSturct: GenericProtocol {
}
struct NewStruct: GenericProtocol {
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.