我用 swift 编写了一个简单的队列类。它是由一个数组实现的。现在我希望它的性能更像内置数组。所以我需要实现[]
运算符但失败了。有人帮忙吗?
public class SimpleQueue<T : Any>
{
private var frontCur = 0
private var reuseCur = -1
private var capacity = 0
private var impl = [T]()
public var count : Int
{
get
{
return impl.count - frontCur
}
}
public func empty() -> Bool
{
return self.count == 0
}
public func size() -> Int
{
return impl.count
}
public func append(o : T)
{
if(frontCur > reuseCur && reuseCur >= 0)
{
impl[reuseCur] = o
reuseCur++
}
else
{
impl.append(o)
}
}
public func pop()
{
frontCur++
}
public func front() -> T
{
return impl[frontCur]
}
public postfix func [](index:Int) -> T //Error!!!!
{
return impl[index + frontCur]
}
}
var x = SimpleQueue<Int>()
for index in 1...10{
x.append(index)
}
print(x.count)
for index in 1...3{
x.pop()
}
print(x.count,x.front(),x[2]) // x[2] Error!!!