August 2016
Intermediate to advanced
1027 pages
23h 11m
English
Let's see how to define a subscript that is used to read and write to a backend array. Reading and writing to a backend storage class is one of the most common uses of custom subscripts, but, as we will see in this chapter, we do not need to have a backend storage class. The following code is a subscript to read and write an array:
class MyNames {
private var names:[String] = ["Jon", "Kim", "Kailey", "Kara"]
subscript(index: Int) -> String {
get {
return names[index]
}
set {
names[index] = newValue
}
}
}As we can see, the syntax is similar to how we can define properties within a class using the get and set keywords. The difference is that we declare the subscript using the subscript keyword. We then specify one ...
Read now
Unlock full access