swiftcustom-operator

How do I implement custom operator [] in swift


I have written a simple queue class in swift. It's implemented by an Array. Now I want this performs more like built-in array.So I need to implement the []operator but failed. Somebody help?

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

Solution

  • 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 is not an operator. Just a method marked with the subscript keyword.

    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.