Skip to content

iOS Protocols with Associated Type

Platform Language License

You have come accross protocol & it's functionalities, you will be addicted to it.

Now we will learn about associatedtype in protocol.

protocol Details {
 var property: String { get set }
}

We can create class as Person

class Person: Details {
    var property = "iOS Developer"
}

You can just call like

let person = Person()
print(person.property)

Output:

iOS Developer

protocol forces class/struct to work with String. But, what if you want property to be Int or Bool.

For this swift has introduced Protocol Associated Types.

In General we can create struct as generic type ,

struct GenericStruct<T> {
 var property: T?
}

let explictStruct = GenericStruct<Bool>()
// T is Bool

let implicitStruct = GenericStruct(property: "iOS Developer")
// T is String

But when you come to protocol we have to use associatedtype.

Let try with above Details example:

protocol Details {
 associatedtype anyType
 var property: anyType { get set }
}

"Associated type = type alias + generics"

class Person: Details {
    var property = "iOS Developer"
}

also you can create a class/struct with some other datatype.

struct Person1: Details {
    var property = 2020
}

Now you can just call

let person = Person()
print(person.property)

Output:

iOS Developer

For Person1

let person1 = Person1()
print(person1.property)

Output:

2020

Download the sample here

AssociatedType.playground

Contents.swift

Github

Reference:

Github

License

AssociatedType.playground is distributed under the MIT license .


Let's grow together 🌱

Cheers 🍻