Subscripts are familiar to anyone who has programmed in Swift, the reason for this being that Array elements are accessed through subscripts (as are Dictionaries).
var array = [1,2,3,4,5]
so array can be accessed with a subscript i.e.
print (array) // prints 1
or the array element can be set
array = 9
changes the element which can then be revealed
print (array) // prints 9
Subscripts have been called glorified computed properties, but they are useful to know and can make reading code much easier.
- Some experience of using the Swift language, including arrays will give some context for subscripts
Subscripts: Shortcuts for accessing elements in a collection, list or sequence. Subscripts can set or retrieve elements without needing separate methods for setting and retrieval. This means that you can quickly and easily access the elements of collections.
Existing subscripts are useful, and can even be used for multi-dimensional arrays.
The a two-dimensional matrix can easily be defined:
var matrix = [[1,2],[3,4]]
The first row can be simply retrieved with:
print (matrix) // 1
print (matrix) // 2
and the second row can be retrieved with:
print (matrix) // 3
print (matrix) // 4
Using a subscript to output Strings
If only enums allowed us to easily convert Integers to Strings. A close version is here, but unfortunately your output is susceptible to out of range errors i.e. the following
var weekDay = EnumDays.init(rawValue: 8)
produces a hard crash out of range error.
Besides that, the init syntax for this is quite unwieldy.
The answer (or a answer) is to use subscripts! This takes the form of the following Gist:
(an alternative implementation of this uses an array as data backing, but once again this has the possibility of introducing out of range errors). Such an implementation is included in the Git link below.
Using a subscript to create a chessboard
Subscripts can make coding easier to read. However they can be tricky to implement, so care needs to be taken. Good Luck!
Apples’ explaination of subscripts: https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html
Here is the Git repo with all of the code above:
Subscripts in Swift for accompanying Medium post. Contribute to stevencurtis/subscriptinswift development by creating…
Want to get in contact? Have questions? Use Twitter: