How To Use A 2D Array in Swift

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts