【发布时间】:2017-05-02 14:37:37
【问题描述】:
我是 Swift 初学者,我有一个关于协议的问题。我遵循了一个教你链表的教程,内容如下:
节点:
class LinkedListNode<Key> {
let key: Key
var next: LinkedListNode?
weak var previous: LinkedListNode?
init (key: Key) {
self.key = key
}
}
还有链表:
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 + "]"
}
}
var description: String 实现只是让您打印链接列表中的每个元素。
到目前为止,我了解了链表的结构,我的问题实际上与链表无关。我不明白的是协议CustomStringConvertible。如果我只有var description: String 实现而不符合协议,为什么会出错?我的意思是,这个协议只是简单地说“嘿,你需要实现var description: String,因为你符合我,但是为什么我们不能在不符合协议的情况下实现var description: String?
是不是因为在后台,有一个函数或某种类型接受 CustomStringConvertible 类型并通过一些代码运行它,瞧!出现文字。
【问题讨论】:
-
我不确定我是否完全理解你的问题——你是在问为什么类型不隐式地符合协议,如果它们恰好实现了它们的所有要求?情况并非如此是有充分理由的,因为大多数协议都有特定的语义要求。例如,
Error协议完全没有要求——但这并不意味着所有类型都是错误的。
标签: swift protocols standards-compliance