How To Use A 2D Array in Swift

2D or multi-dimensional arrays are useful in many contexts.

How To Use 2D Arrays In Swift With Code Examples

To define a multi dimensional array, use double the square brackets like so:

var arr = [[String]]

Then you can add arrays to this array:

var boyNames = ["Eddy", "David", "Ryan", "Joel", "Andrew"]
var girlNames = ["Karen", "Angela", "Holly", "Jessica", "Jennifer"]
arr.append(boyNames)
arr.append(girlNames)
print(arr)

This is the output:

[["Eddy", "David", "Ryan", "Joel", "Andrew"], ["Karen", "Angela", "Holly", "Jessica", "Jennifer"]]

To access one array at a time you cause use square brackets like this:

print(arr[0])
["Eddy", "David", "Ryan", "Joel", "Andrew"]

If you want to access one element, you can use two square brackets:

print(arr[0][0])
Eddy

That’s how you use 2-d arrays.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts