Multi-dimensional arrays
For single-dimensional arrays, Swift by Example is an excellent document (although read ‘count’ where you see ‘endindex’). For multi-dimensional arrays, I couldn’t find anything of substance. As a learning experience, I created my own exposé on multi-dimensional arrays…
An analogy is to think of a typical bookcase with shelves, each holding a different number of books.
Consider the first shelf with Shakespeare books King Lear, Macbeth and Hamlet, the second shelf with children’s books The Cat in the Hat, and Winnie-the-Pooh, and the third shelf containing the classics To Kill a Mockingbird, Pride and Prejudice, Gone with the Wind, Animal Farm, and Wuthering Heights.
We could declare and initialise the array with:
let bookcase = [["King Lear","Macbeth","Hamlet"], ["The Cat in the Hat","Winnie-the-Pooh"],["To Kill a Mockingbird","Pride and Prejudice","Gone with the Wind","Animal Farm","Wuthering Heights"]]
The first shelf/row has 3 items, the second shelf/row has 2 items, and the third shelf has 5 items. bookcase[0] refers to the first row of Shakespeare books, and is a single-dimensional array. bookcase[1] is likewise a single-dimensional array and refers to the children’s books.
To add another Shakespearian book, we could use:
bookcase[0] += ["The Tempest"]
Notice that we are adding a single-dimensional array to a single-dimensional array. There are now four Shakespearian books on the shelf/in the first row of the array. bookcase[0] now equals [“King Lear”,”Macbeth”,”Hamlet”,”The Tempest”], and is a one-dimensional array. bookcase is a two-dimensional array, with bookcase[0] being it’s first row.
OR…