Reputation: 3
I want to determine whether my linked-list is empty or not, however, I cannot do this by checking head.next==tail because I will get an error that binary operator "==" cannot be applied to operations of type 'LLNode?'.
import Foundation
class LLNode<T> {
var key: T!
var next: LLNode?
var previous: LLNode?
}
public class LinkedList<T: Equatable> {
private var head: LLNode<T> = LLNode<T>()
private var tail: LLNode<T> = LLNode<T>()
init() {
head.next = tail
head.previous = tail
tail.next = head
tail.previous = head
}
func isEmpty() {
return head.next == tail ? true : false
}
}
Upvotes: 0
Views: 1653
Reputation: 93191
You can make LLNode
conform to the Equatable
protocol but this implies that you must constraint T: Equatable
for all LLNode
too.
If I were to make minimal changes to your code to make it works, here's how I would it:
func isEmpty() -> Bool {
if let next = head.next where next.key == tail.key {
return true
} else {
return false
}
}
Upvotes: 0
Reputation: 1322
In this case, you should probably be checking if head
and tail
are the same instance by using the ===
operator. Note that this is different than testing for equality in Swift.
==
checks for object equality, which you have to define yourself, whereas ===
determines if the two variables refer to the same instance. Your check should therefore look like:
func isEmpty() -> Bool {
return head.next === tail
}
The ternary operator is not necessary, as comparison operators already return a Bool.
Upvotes: 3