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.
A subscript defines a shortcut to elements of a collection, list, or sequence. It can be defined in classes, structures, and enumerations to allow quick access to elements from a certain type.
Array Subscripts An array subscript allows Mathcad to display the value of a particular element in an array. It is used to refer to a single element in the array. The array subscript is created by using the [ key. This is referred to as the subscript operator.
What is a multidimensional subscript in Swift? Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval.
It looks like there are 2 questions here.
subscripting
on my own custom class?To enable subscripting
on your class Container
you need to implement the subscript
computed property like this.
class Container { private var list : [Any] = [] // I made this private subscript(index:Int) -> Any { get { return list[index] } set(newElm) { list.insert(newElm, atIndex: index) } } }
Now you can use it this way.
var container = Container() container[0] = "Star Trek" container[1] = "Star Trek TNG" container[2] = "Star Trek DS9" container[3] = "Star Trek VOY" container[1] // "Star Trek TNG"
Container
that supports subscripting writing something like data[1][2]
?If we use your example no, you cannot. Because data[1]
returns something of type Any
. And you cannot subscript Any
.
But if you add a cast it becomes possible
var container = Container() container[0] = ["Enterprise", "Defiant", "Voyager"] (container[0] as! [String])[2] // > "Voyager"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With