Multidimensional Array Example in Swift

In this tutorial, you will learn how to create both a one-dimensional and multidimensional arrays in Swift.

After reading this tutorial, you might also be interested in learning how to use FlatMap and Map when working with arrays.

One-Dimensional Array

Creating a one-dimensional array in Swift is very simple. Below is an example of how to create an empty one-dimensional array that can hold String data types.

var countries = [String]()

Creating a single dimensional array with initial values is also very easy.

var countries = ["Canada", "Russia", "Japan"]

Compare the two code snippets above with the code snippets below that demonstrate how to create a multidimensional array or array of arrays in Swift.

Multidimensional Array in Swift

Creating a multidimensional array in Swift is as simple as creating a one-dimensional array. Just think of it as an Array of Arrays.

Create an empty multidimensional array

Below is an example of how to create an empty multidimensional array that can hold String data types.

var citiesOfCanada = [[String]]()

A multidimensional array with initial values

Creating an array of arrays that holds initial values is also very simple.

var citiesOfCanada = [
    ["Vancouver", "Victoria", "Kelowna"],
    ["Ottawa", "Toronto", "Hamilton"],
    ["Edmonton", "Calgary", "Red Deer"]
]

Notice that a multidimensional array is just an array of arrays. Printing the above array of arrays will give the following result.

[["Vancouver", "Victoria", "Kelowna"], ["Ottawa", "Toronto", "Hamilton"], ["Edmonton", "Calgary", "Red Deer"]]

Adding Values to Multidimensional Array

You can create an empty array and then add as many as you like new arrays to it one by one this way.

var citiesOfCanada = [[String]]()

var britishColumbiaProvince = ["Vancouver", "Victoria", "Kelowna"]
var ontarioProvince = ["Ottawa", "Toronto", "Hamilton"]
var albertaProvince = ["Edmonton", "Calgary", "Red Deer"]

citiesOfCanada.append(britishColumbiaProvince)
citiesOfCanada.append(ontarioProvince)
citiesOfCanada.append(albertaProvince)

print(citiesOfCanada)

Printing the above array will give the following results.

[["Vancouver", "Victoria", "Kelowna"], ["Ottawa", "Toronto", "Hamilton"], ["Edmonton", "Calgary", "Red Deer"]]

Here is how the above Swift code snippet looks and works in Xcode Playground.

Multidimensional Array in Swift

I hope this short Swift tutorial was helpful for you. Have a look around this site for other Swift tutorials. Hopefully, you will find other tutorials that will be helpful to you.

Happy coding!

Leave a Reply

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