The View Protocol | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18272812-swiftui-fundamentals/lessons/2

tell me about the associated type

@unique4sourav Thanks very much for your question!

An associatedType in Protocols is a placeholder value that you state, but don’t specify when you create your protocol. The actual value of the associatedType is provided by the struct or class which implements the protocol.

For example, I can define the following protocol:

protocol Test {
    associatedtype Element
    var items: [Element] { get set }
}

Now, in the protocol, Element has no real definition. This means that if I am to implement this protocol, then I must also provide a concrete type in place of “Element”. I would do so like this:

class Main: Test {
    typealias Element = String
    var items = [String]()
}

The nice thing about Swift is that it is smart enough to figure out in our example that because items is originally defined in the “Test” protocol, and in the class implementing “Test”, items is an array of Strings, the compiler can infer what type “Element” is without having to explicitly defining it. Thus, we can simplify the class definition even further:

class Main: Test {
    var items = [String]()
}

I hope this helps!

All the best :slight_smile:

Hello,

I can’t find the links that you mentioned about ‘the Swift behind SwiftUI’.

Thanks in advance.

@catie : I can’t find the links that you mentioned about ‘the Swift behind SwiftUI’.

Thanks in advance :slight_smile:

Yes the reference links are missing @catie