I am beginner with the Swift having no advance knowledge with operators.
I have the following class
class Container {
var list: [Any] = [];
}
I want to implement the operator subscript [] in order to access the data from list.
I need something like this:
var data: Container = Container()
var value = data[5]
// also
data[5] = 5
Also I want to be able to write something like this:
data[1][2]
Is it possible considering that element 1 from Container is an array?
Thanx for help.
It looks like there are 2 questions here.
1. How can I enable
subscriptingon my own custom class?To enable
subscriptingon your classContaineryou need to implement thesubscriptcomputed property like this.Now you can use it this way.
2. Can I access one element of
Containerthat supports subscripting writing something likedata[1][2]?If we use your example no, you cannot. Because
data[1]returns something of typeAny. And you cannot subscriptAny.But if you add a cast it becomes possible