I am taking a Data Structures course in Java and to help myself learn Swift I am trying to complete the same assignments I have already done in Java in Swift. I am having some trouble comparing Objects in Swift. In Java, I have the following ArrayList Class with a remove(E obj) method:
public E remove(E obj) {
if (currentSize == 0){
return null;
}
for (int i=0; i<currentSize; i++)
if (((Comparable<E>)storage[i]).compareTo(obj) == 0) {
E removedElement = storage[i];
for (int j = i;j<currentSize-1;j++) {
storage[j] = storage[j+1];
}
currentSize--;
if (currentSize < 0.25*maxSize)
shrinkStorage();
return removedElement;
}
return null;
}
This goes through the list and casts each element in the list to Comparable and compares it to the object.
Now, translating this into Swift I created the a ArrayLinearList structure and made this function
mutating func remove(obj: E) -> E? {
if currentSize == 0 {
return nil
}
for var i = 0; i < currentSize; i++ {
if storage[i] == obj {
let removedElement = storage[i]
for var j = 1; j < currentSize-1; j++ {
storage[j] = storage[j+1]
}
currentSize--
if currentSize < maxSize/4 {
shrinkStorage()
}
return removedElement
}
}
return nil
}
I read the documentation on the Comparable and Equatable interface online but it was my understanding that the implementation of the Comparable and Equatable interface should be in the actual class to be used. on this line
if storage[i] == obj {
Cannot invoke '==' with an argument list of type '($T6,E)'
What is the proper way to set this up so I can compare generic objects in my structure? In case it is important, the generic array is declared as:
var storage = [E]()
for i in 0..<currentSize { ... }.Comparable<E>. Also, doing.compareTo()and then checking== 0is silly and you should always do.equals()instead.