return nil 或方法存根中的类似内容

return nil or something similar in method stub

我正在 java 课程中学习数据结构,为了好玩和学习,我正在尝试编写 Swift 中的内容。我正在尝试实施协议,但在设置方法存根时遇到问题。我尝试返回 nil 但没有用,但现在我收到此错误:

"Swift Compiler Error 'E' is not convertible to 'E'"

这很奇怪。这是基于通用数组的列表的代码。这是我目前所拥有的:

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 {

    }

}

编辑:我刚刚发现错误。使用 Jesper 的建议,我发现我没有在 Swift 中正确编写协议。看着这个答案

how to create generic protocols in swift iOS?

我现在可以让它工作了。谢谢 Jesper!

您不应在这些方法上使用类型参数 E - 它将被视为与结构中的类型参数不同的类型参数。删除这些方法定义中的 <E>,将使用来自结构本身的那个。

此外,您可能必须向 E 添加约束,以便您确定它实现了 NilLiteralConvertible(如 Optional),否则您无法 return nil 来自一个应该 return a E.

的函数

我刚发现错误。使用 Jesper 的建议,我发现我没有在 Swift 中正确编写协议。看着这个答案

How to create generic protocols in Swift?

我现在可以让它工作了。谢谢 Jesper!