Your own subscript in Swift

Image for post
Image for post

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).

For example

var array = [1,2,3,4,5]

so array can be accessed with a subscript i.e.

print (array[0]) // prints 1

or the array element can be set

array[0] = 9

changes the element which can then be revealed

print (array[0]) // 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


Member elements:

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.

The problem

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

Image for post
Image for post
A two dimensional Array in swift

The first row can be simply retrieved with:

print (matrix[0][0]) // 1

print (matrix[0][1]) // 2

and the second row can be retrieved with:

print (matrix[1][0]) // 3

print (matrix[1][1]) // 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:

Here is the Git repo with all of the code above:

Want to get in contact? Have questions? Use Twitter:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store