Multi-dimensional Arrays

We can create an array and add each shelf/row one at a time. [This is for illustration purposes only, and not the most efficient way.]

var bookcase2 = [[String]]()

bookcase2 is a 2-dimensional array with no elements.

bookcase2 += [["King Lear","Macbeth","Hamlet"]]
// we could have used bookcase2.append(["King Lear","Macbeth","Hamlet"])

bookcase2 now has 1 row of 3 books.

bookcase2 += [[]]

Note that bookcase2 is a 2-dimensional array, and we can only add another 2-dimensional array, thus the double square brackets on the RHS. bookcase2 now has two rows, although the second row (bookcase2[1]) has no books. bookcase2.count will return 2; bookcase2[0].count will return 2; and bookcase2[1].count will return 0.

bookcase2[1] += ["The Cat in the Hat","Winnie-the-Pooh"]

The second row now contains two books/elements. bookcase2[1] is a one-dimensional array, and hence, the array on the RHS is a one-dimensional array. bookcase2.count will return 2 because bookcase2 has 2 rows, and bookcase2[1].count will return 2 because the second row/shelf contains 2 books.

The children’s books were added to the array in two steps for illustrative purposes. We’ll add the third row in one step…

bookcase2 += [["To Kill a Mockingbird","Pride and Prejudice","Gone with the Wind","Animal Farm","Wuthering Heights"]]

Notice again, bookcase2 is a 2-dimensional array, so we need to add to it another 2 dimensional array, and hence, the two square brackets on the RHS.

bookcase2 now has the same contents as bookcase, except for one book. Which one?

Leave a Reply

Your email address will not be published. Required fields are marked *