This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18272812-swiftui-fundamentals/lessons/2
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
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
Yes the reference links are missing @catie