跨集合扩展自定义字符串可转换



我在 swift 中实现了一个链表——我还构建了一个堆栈和队列,它们都使用底层的链表。我扩展了我的链表以符合自定义字符串可转换协议,因此我可以在其上调用 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
}
}

如何在不重写协议扩展的情况下将此功能扩展到我的队列/堆栈?我的队列文件如下所示:

class Queue <T> {
    private var list = LinkedList<T> ()
    var isEmpty: Bool {
        return list.isEmpty
    }

其次是我选择实现的任何功能。在 VC 或其他地方调用 print(newQueue) 永远不会调用 linkedList customstringconvertible 扩展...不知道为什么。我需要将链表子类化为队列/堆栈吗?我来自 Objc 背景,不太关注协议和扩展。

Queue不是

LinkedList的子类,所以它不继承description属性。您必须实现协议对于该类也是如此,但当然您可以"转发"到LinkedList的描述:

extension Queue: CustomStringConvertible {
    var description: String {
        return list.description
    }
}

最新更新