gpt4 book ai didi

swift - 如何快速实现自定义运算符 []

转载 作者:搜寻专家 更新时间:2023-11-01 06:41:57 24 4
gpt4 key购买 nike

我用 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!!!

最佳答案

apple docs

Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name. Their syntax is similar to both instance method syntax and computed property syntax. You write subscript definitions with the subscript keyword, and specify one or more input parameters and a return type, in the same way as instance methods.


下标不是运算符。只是一个用 subscript 关键字标记的方法。

subscript (index:Int) -> T {
return impl[index + frontCur]
}

Read this:

class MyColl {

private var someColl : [String] = []

subscript(index: Int) -> String {
get {
return someColl[index]
}
set(value) {
someColl[index] = value
}
}
}

And read this:

Swift has a well-designed and expansive suite of built-in collection types. Beyond Array, Dictionary, and the brand new Set types, the standard library provides slices, lazy collections, repeated sequences, and more, all with a consistent interface and syntax for operations. A group of built-in collection protocols—SequenceType, CollectionType, and several others—act like the steps on a ladder. With each step up, a collection type gains more functionality within the language and the standard library.

关于swift - 如何快速实现自定义运算符 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com