Swift version: 5.1
Creating an array that holds strings is as simple as writing
[String], but what about creating an array where each item is an array of strings – an array of arrays? This is called a multi-dimensional array, because if you were to draw its contents on paper it would look like a grid rather than a line.
In Swift, creating a multi-dimensional array is just a matter of adding another set of brackets. For example, to turn our
[String] array into an array of arrays, you would just write
[[String]]. But be careful: arrays are value types, which means if you add an array to another array, then modify it, only one of the two copies will be changed.
The code below demonstrates creating an array of arrays, where each inner array holds strings. It also demonstrates the value type situation that might catch you out:
// this is our array of arrays var groups = [[String]]() // we create three simple string arrays for testing var groupA = ["England", "Ireland", "Scotland", "Wales"] var groupB = ["Canada", "Mexico", "United States"] var groupC = ["China", "Japan", "South Korea"] // then add them all to the "groups" array groups.append(groupA) groups.append(groupB) groups.append(groupC) // this will print out the array of arays print("The groups are:", groups) // we now append an item to one of the arrays groups.append("Costa Rica") print("\nAfter adding Costa Rica, the groups are:", groups) // and now print out groupB's contents again print("\nGroup B still contains:", groupB)
print() statement will still print out "Canada, Mexico, United States" because of array's value type behavior: we modified the copy of the array that was inside
SPONSORED Why the top iOS apps rely on Instabug for crash reporting. Crash reporting + Bug reporting + Customizable in-app surveys all in one SDK. Know which line of code caused the crash along with network logs, repro steps, and the session profiler to identify and resolve severe crashes quickly. See more detailed features comparison and try Instabug for free here.
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.