我正在学习 Java 数据结构类(class),为了乐趣和学习,我尝试用 Swift 编写这些内容。我正在尝试实现一个协议(protocol),但在设置方法 stub 时遇到问题。我尝试返回 nil 但这不起作用,但现在我收到此错误:
“Swift 编译器错误 'E' 无法转换为 '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 中正确编写协议(protocol)。看看这个答案”
how to create generic protocols in swift iOS?
我现在可以让它工作了。谢谢杰斯珀!
最佳答案
您不应该有类型参数 E
在这些方法上 - 它将被视为与结构上的类型参数不同的类型参数。删除<E>
在这些方法定义中,将使用结构本身的定义。
此外,您可能必须向 E
添加约束这样您就可以确定它实现了 NilLiteralConvertible
(就像一个Optional),否则你不能返回 nil
来自应该返回 E
的函数.
关于swift - 在方法 stub 中返回 nil 或类似的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29167521/