I am taking a data structures in java course and for fun and learning I am trying to write the stuff in Swift. I am trying to implement a protocol but I am having trouble setting up the method stubs. I tried returning nil but that didn't work but now I am getting this error:
"Swift Compiler Error 'E' is not convertible to 'E'"
That is strange. This is code for a generic array based list. This is what I have so far:
struct ArrayLinearList<E>: LinearListADT {
let DEFAULT_MAX_SIZE = 100;
var currentSize: Int
var maxSize: Int
var storage = [E]()
init(sizeOfList: Int) {
currentSize = 0
maxSize = sizeOfList
storage = [E]()
}
mutating func addFirst<E>(obj: E) {
}
mutating func addLast<E>(obj: E) {
}
mutating func insert<E>(obj: E, location: Int) {
}
mutating func remove<E>(location: Int) -> E {
return storage[location] //***This is where I get the above error
}
mutating func remove<E>(obj: E) -> E {
return nil //I tried this but that didn't work either
}
mutating func removeFirst<E>() -> E? {
return nil //I also tried this but that didn't work
}
mutating func removeLast<E>() -> E? {
return nil
}
mutating func get<E>(location: Int) -> E? {
return nil
}
mutating func contains<E>(obj: E) -> Bool {
return false
}
mutating func locate<E>(obj: E) -> Int? {
return nil
}
mutating func clear<E>() {
}
mutating func isEmpty<E>() -> Bool {
}
mutating func size<E>() -> Int {
}
}
EDIT: I just found the mistake. Using the suggestion from Jesper I then found out that I did not write the protocol properly in Swift. Looking at this answer"
how to create generic protocols in swift iOS?
I was able to get it working now. Thank you Jesper!