跨集合扩展 customstringconvertible
extending customstringconvertible across collections
我在 swift 中实现了一个链表 - 我还构建了一个堆栈和队列,它们都在底层使用了链表。我扩展了我的链接列表以符合 customstringconvertible 协议,因此我可以在其上调用 print(list) 。扩展名包含在我的 linkedlist.swift 文件中,如下所示:
extension LinkedList: CustomStringConvertible {
var description: String {
var currentIndex: Int = 0
var description: String = ""
if var currentNode = self.head {
// while currentNode != nil {
for _ in 0...count-1 {
//description += (String(currentNode.value) + " " )
description += ("\"" + (String(currentNode.value)) + "\"" + " is at index: \(currentIndex)\n")
if let nextNode = currentNode.next {
currentNode = nextNode
currentIndex += 1
}
}
}
return description
}
}
如何在不重写协议扩展的情况下将此功能扩展到我的 queue/stack?我的队列文件如下所示:
class Queue <T> {
private var list = LinkedList<T> ()
var isEmpty: Bool {
return list.isEmpty
}
后面是我选择实现的任何功能。在 VC 或其他地方调用 print(newQueue) 从不调用 linkedList customstringconvertible 扩展...不知道为什么。我需要将链表子类化为 queue/stack 吗?我来自 Objc 背景,不太关注协议和扩展。
Queue
不是 LinkedList
的子 class,因此它不继承
description
属性。你必须实施协议
对于那个 class 也是如此,但是你当然可以 "forward"
LinkedList
的描述:
extension Queue: CustomStringConvertible {
var description: String {
return list.description
}
}
我在 swift 中实现了一个链表 - 我还构建了一个堆栈和队列,它们都在底层使用了链表。我扩展了我的链接列表以符合 customstringconvertible 协议,因此我可以在其上调用 print(list) 。扩展名包含在我的 linkedlist.swift 文件中,如下所示:
extension LinkedList: CustomStringConvertible {
var description: String {
var currentIndex: Int = 0
var description: String = ""
if var currentNode = self.head {
// while currentNode != nil {
for _ in 0...count-1 {
//description += (String(currentNode.value) + " " )
description += ("\"" + (String(currentNode.value)) + "\"" + " is at index: \(currentIndex)\n")
if let nextNode = currentNode.next {
currentNode = nextNode
currentIndex += 1
}
}
}
return description
}
}
如何在不重写协议扩展的情况下将此功能扩展到我的 queue/stack?我的队列文件如下所示:
class Queue <T> {
private var list = LinkedList<T> ()
var isEmpty: Bool {
return list.isEmpty
}
后面是我选择实现的任何功能。在 VC 或其他地方调用 print(newQueue) 从不调用 linkedList customstringconvertible 扩展...不知道为什么。我需要将链表子类化为 queue/stack 吗?我来自 Objc 背景,不太关注协议和扩展。
Queue
不是 LinkedList
的子 class,因此它不继承
description
属性。你必须实施协议
对于那个 class 也是如此,但是你当然可以 "forward"
LinkedList
的描述:
extension Queue: CustomStringConvertible {
var description: String {
return list.description
}
}