0

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!

Community
  • 1
  • 1
Guillermo Alvarez
  • 1,695
  • 2
  • 18
  • 23

2 Answers2

1

You shouldn't have a type parameter E on those methods - it will be considered a separate type parameter from the one on the struct. Remove the <E> in those method definitions and the one from the struct itself will be used.

In addition, you may have to add a constraint to E so that you are sure that it implements NilLiteralConvertible (like an Optional), otherwise you can't return nil from a function that is supposed to return a E.

Jesper
  • 7,477
  • 4
  • 40
  • 57
0

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?

I was able to get it working now. Thank you Jesper!

Community
  • 1
  • 1
Guillermo Alvarez
  • 1,695
  • 2
  • 18
  • 23