An array typically contains items of the same data type such as strings or integers. To declare an array to hold a specific data type, you just need to state the data type inside square brackets like this:
Then you can just add items to the array using the append command like this:
You can also define an array just by stuffing it with data right away like this:
Once you fill an array with data, you can sort it using the sorted() method like this:
This would create a sorted array that contains [“bear”, “duck”, “tiger”]. In the above code, the array appears sorted but the original beasts array is actually still unsorted. If you want to save the sorted results, you must store them in a new variable like this:
In this code, newArray is defined as an array of String data types. Then the sorted() data gets stored in the newArray variable.
Of course, you could just declare a new variable and store the sorted results in that new variable in one line. In the above example, sameArray is defined and given a value of sorted array data all in one line.
Typically an array doesn’t contain just one data type like a String or Int, but a structure that contains multiple fields such as the following:
This code creates an array of structures called Contacts where each Contact contains a first, last, and phone field that can hold a String data type. To create a structure, you need to define a variable and data for each field in that structure like this:
This creates three variables (employee, prospect, and salesContact) that each contain a first, last, and phone string data. To add these structures to an array, you can just use the append command like this:
This creates an array that holds three structures. The first structure in the array is the name “Fred Zimmerman,” the second structure is “Susan Acker” and the third structure is “Bill Miller.”
Now to sort this array, you must specify the field to sort on. If we wanted to sort by the “last” field, you would use the sorted command like this:
The above code would create sortedContacts array where the first structure is the name “Susan Acker,” the second structure is “Bill Miller” and the third structure is “Fred Zimmerman.”
The entire code for defining a structure, creating variables to store data in structures, creating an array of structures, and then sorting that array of structures would look like this in a Swift playground:
With an array of structures, you can sort on individual fields.