I am a beginner Swift learner and I have a question about protocols. I have followed a tutorial that teaches you about linked lists, which is as follows:
Node:
class LinkedListNode<Key> {
let key: Key
var next: LinkedListNode?
weak var previous: LinkedListNode?
init (key: Key) {
self.key = key
}
}
And the linked list:
class LinkedList<Element>: CustomStringConvertible {
typealias Node = LinkedListNode<Element>
private var head: Node?
// irrelevant code removed here
var description: String {
var output = "["
var node = head
while node != nil {
output += "\(node!.key)"
node = node!.next
if node != nil { output += ", " }
}
return output + "]"
}
}
The var description: String
implementation simply lets you to print each elements in the linked list.
So far, I understand the structure of the linked list, my problem isn't about the linked list actually. What I don't understand is the protocol CustomStringConvertible
. Why would it be wrong if I have only the var description: String
implementation without conforming to the protocol? I mean, this protocol just simply say "Hey, you need to implement var description: String
because you are conformed to me, but why can't we just implement var description: String
without conforming to the protocol?
Is it because in the background, there is a function or some sort that takes in a type CustomStringConvertible
and run it through some code and voila! text appears.