W2021 Two-Dimensional Arrays

From Coder Merlin
Revision as of 07:40, 28 October 2021 by Paolo-besabella (talk | contribs) (Created page with "Two-dimensional arrays are Swift arrays whose elements are other arrays. However, this is not the only interesting property of two-dimensional arrays. Two-dimensional arrays i...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Two-dimensional arrays are Swift arrays whose elements are other arrays. However, this is not the only interesting property of two-dimensional arrays. Two-dimensional arrays in Swift are very similar to matrices in math.

The benefit of using two-dimensional arrays is that they are very efficient when working with data organized in rows and columns. The problem with using one-dimensional arrays is that they are not efficient when working with data organized this way.

As an example, consider the following one-dimensional array representing a deck of cards where each index represents a card:

var deckOfCards = [Card]()

The deck of cards is not useful yet because it is empty. Now suppose you need to fill the first four cards with data. This could be done as follows:

deckOfCards.append(Card(rank: .Ace, suit: .Spades)) // 1st card 

deckOfCards.append(Card(rank: .Two, suit: .Clubs)) // 2nd card 

deckOfCards.append(Card(rank: .Three, suit: .Diamonds)) // 3rd card 

deckOfCards.append(Card(rank: .Four, suit: .Hearts)) // 4th card 

To access the data in any of these cards you would have to write code similar to this:

var firstCard = deckOfCards.first 

var secondCard = deckOfCards.dropFirst().first

The .first property returns the first element of a Swift array, which is not very intuitive if you are not familiar with arrays. Similarly, the .dropFirst() method returns a new array without the first element. This means that if you want to get any of the data stored in these 4 cards, you need to know both the indices of this data and which method was used to drop the first element of an array (in this case .first).

Curriculum[edit]

ExercisesIcon.png
 Coder Merlin™  Computer Science Curriculum Data

Unit:

Experience Name: W2021 Two-Dimensional Arrays ()

Next Experience: ()

Knowledge and skills: noneSome use of "" in your query was not closed by a matching "".

Topic areas: none

Classroom time (average):

Study time (average):

Successful completion requires knowledge: none

Successful completion requires skills: none

Motivation for Using Two-Dimensional Arrays in Swift[edit]

The newer versions of Swift bring many improvements and enhancements to the language, which help beginners and professionals alike write better code with less effort, leading to a more pleasant user experience. One of these new features is the possibility of declaring arrays of an arbitrary type, rather than only of the types that have been available since Swift was first introduced. However, this new feature doesn't provide any new functionality, but rather it makes existing code easier to write and maintain.

Most programming languages that support arrays of arbitrary type use some form of the generic array where each element must be of the same type. For example, when using Swift to create an array with three i32 elements, one would write:

let intArray: [Int] = [1, 2, 3]

This array is polymorphic in the sense that it can hold any integer value. However, when dealing with arrays containing objects of different types, this type-safety must be relaxed in order to avoid a situation where the compiler forces us to add a cast for each object contained inside the array.

Even though the compiler is aware of each object's type being inserted into the array, it does not flag any errors when these lines are compiled. Two-dimensional arrays allow us to work around this problem by declaring a type for each of its dimensions, i.e., each row and column.

By doing so, the compiler will raise an error if the types contained in a given row or column do not match those declared for that dimension. This allows us to have greater control over the creation of arrays whose elements consist of an arbitrary number of different types.

Declaring and Initializing Multi-Dimensional Arrays in Swift[edit]

As with single-dimensional arrays, multi-dimensional arrays can be initialized either at the declaration or upon initialization.

In this case, the compiler will raise an error if either of these dimensions is not a positive integer.

However, as with any value type of Array type, it is possible to initialize the array with any given set of values enclosed in an array literal or dictionary literal.

CoderMerlin™ Code Explorer: W0000 (1) 🟢


One thing to keep in mind when initializing an array of arrays (i.e., a two-dimensional array) is that the inner arrays must all have the same length. This is because multi-dimensional arrays are just a special case of Array where each element is another Array.

However, unlike other programming languages that support two-dimensional arrays, Swift doesn't allow us to increase the size of an array by adding new rows or columns after its creation. Rather, it forces us to either initialize the array with a predefined length or add elements one at a time.

let intArray: [Int] = [1, 2, 3]

This array is polymorphic in the sense that it can hold any integer value. However, when dealing with arrays containing objects of different types, this type-safety must be relaxed in order to avoid a situation where the compiler forces us to add a cast for each object contained inside the array.

Even though the compiler is aware of each object's type being inserted into the array, it does not flag any errors when these lines are compiled. Two-dimensional arrays allow us to work around this problem by declaring a type for each of its dimensions, i.e., each row and column.

By doing so, the compiler will raise an error if the types contained in a given row or column do not match those declared for that dimension. This allows us to have greater control over the creation of arrays whose elements consist of an arbitrary number of different types.

Declaring and Initializing Multi-Dimensional Arrays in Swift[edit]

As with single-dimensional arrays, multi-dimensional arrays can be initialized either at the declaration or upon initialization.

In this case, the compiler will raise an error if either of these dimensions is not a positive integer.

However, as with any value type of Array type, it is possible to initialize the array with any given set of values enclosed in an array literal or dictionary literal.

CoderMerlin™ Code Explorer: W0000 (2) 🟢


One thing to keep in mind when initializing an array of arrays (i.e., a two-dimensional array) is that the inner arrays must all have the same length. This is because multi-dimensional arrays are just a special case of Array where each element is another Array.

However, unlike other programming languages that support two-dimensional arrays, Swift doesn't allow us to increase the size of an array by adding new rows or columns after its creation. Rather, it forces us to either initialize the array with a predefined length or add elements one at a time.

Accessing Multi-Dimensional Arrays in Swift[edit]

One way of accessing an element from a two-dimensional array is by using subscript syntax, just as we would with any other type of array.

CoderMerlin™ Code Explorer: W0000 (3) 🟢


However, subscripts are limited to one-based indexing. This means that the first row or column of a two-dimensional array starts at index 1 instead of 0.

The way around this problem is by using another form of subscript syntax with an optional base parameter (i.e., the number to start counting from) which defaults to zero.

multiDimensionalArray [2][1] = 6 // this is equivalent to multiDimensionalArray [2].0 [1].0 = 6

The following code shows how we would access an item in a nested array of arrays, where some of the elements are initialized with values and others are simply placeholders.

multiDimensionalArray [1] = [[7, 8], 60] // this is equivalent to multiDimensionalArray .0 [1] .0 = [[7, 8], 60]

The first multi-dimensional array has two dimensions ( i.e., each element is another array), and the first row has two elements. The first element of this first row is initialized by assigning it a value of 7 whereas the second element is initialized as a placeholder with the value 60.

Traversal of Multi-Dimensional Arrays in Swift[edit]

Swift has made multi-dimensional arrays much easier to manage. You can think of it as managing a grid where each row is an individual array, potentially with different lengths and the columns are indexes into the rows.

For example, you might have a 2D array where the first dimension is 3 elements long and the second dimension is 4 elements long. This would result in multiple arrays, one for each row in the grid.

Each of the inner arrays is a reference to an instance of that grid (i.e. an array). You can then adjust various elements in the multidimensional array like this:

CoderMerlin™ Code Explorer: W0000 (4) 🟢


This is a great way to work with multi-dimensional arrays.

Searching for an Element in a Multi-Dimensional Array in Swift[edit]

You can then use this to search for an element in the multi-dimensional array. This will return a Subscript Index (an Element) which you can then either store and adjust:

CoderMerlin™ Code Explorer: W0000 (5) 🟢


Insertion of an Element in a Multi-Dimensional Array in Swift[edit]

You can insert an element into a multi-dimensional array at a specified index. This will then return the new index of that reference in the updated array:

CoderMerlin™ Code Explorer: W0000 (6) 🟢


Deleting an Element in a Multi-Dimensional Array in Swift[edit]

To delete an element from a multi-dimensional array, you need to know the index of the reference.

For example:

CoderMerlin™ Code Explorer: W0000 (7) 🟢


Conclusion[edit]

To conclude, multi-dimensional arrays in Swift are a lot easier to manage because of the support for Subscript Indices.

This allows you to work with data organized as a grid. You can search, update and delete elements from this grid very easily by knowing their indices.

In addition, having setter access to these multi-dimensional arrays is nice because you can adjust the size of the grid dynamically.

These are some points that I found really helpful when working with multi-dimensional arrays in Swift and working with these grids.