【发布时间】:2017-01-12 09:37:25
【问题描述】:
我目前正在尝试一些基本的数据结构,例如 LinkedList。我定义了一个 ListNode 类的泛型值,如下所示:
class ListNode<T> {
var nodeContent: T
var nextNode: ListNode<T>? = nil
init() {
// details omitted here
}
然后是一个链表。我想实现 contains() 方法,所以我有这样的东西:
func contains<T>(_ item: T) -> Bool {
var currNode = self.head
while (currNode != nil) {
if currNode?.nodeContent == item {
return true
}
currNode = currNode?.nextNode
}
return false
}
然后它给我一个错误,说 '==' 不能应用于 T 和 T 类型。然后我查看了语言指南并将 ListNode 类和 LinkedList 结构更改为:
class ListNode<T: Equatable>{}
struct LinkedList<T: Equatable>{}
但它不起作用,所以我在 func 本身中添加了 'Equatable':
func contains<T: Equatable>(_ item: T) -> Bool
仍然失败。我尝试将语言指南中的示例函数粘贴到里面,
func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
没有错误发生。我可以知道为什么会这样吗?我尝试搜索,但像this 这样的所有建议答案都无法消除我的疑虑。提前致谢!
【问题讨论】:
-
请注意,在
LinkedList或ListNode的实际声明中,不需要将T限制为Equatable(链接列表没有具有 到有Equatable元素)——最好实现一个扩展where T : Equatable,并在那里定义你的contains函数(你也可以为不受约束的T定义谓词版本,就像stdlib 一样)。 -
尽管如此,最好将
LinkedList与Sequence或Collection保持一致。您将免费获得所有这些(以及更多)。