Introduction
Swift has two types of collections namely arrays and dictionaries for storing collections of values. An array stores an ordered list of values of the same type. Dictionaries store unordered collections of values of the same type. The insertion of the wrong type into an array is not possible. Swift's use of explicitly typed collections ensures the code is always clear about the types of values it works with and enables it to catch any type of mismatches in code development.
Arrays
An array stores multiple values of the same type in ordered list and the same value can appear in an array multiple times at different positions. A swift array is specific about the kinds of values they store. It can store any kind of object and do not provide any information about the nature of objects. The type of values that a particular array can store is always made clear. Array <type> where type is the type that the array is allowed to store.
Array literals
The initialization of an array with an array is literal to write one or more values as an array collection. An array literal is written as a list of values, separated by commas surrounded by a pair of square brackets. In the below example the list is a variable declared as an array of string values and it has the values stored in it.
- var list: String[] = ["book","pen"]
Accessing and Modifying an Array
Accessing and modifying an array can be done by method and properties using subscript syntax. The boolean isEmpty property used for checking the count property is equal to 0. The subscript syntax is used to change the range of values, even the replacement set of values has a different length than the range that it is replacing.
- if shoppingList.isEmpty
- {
- println ("The List is empty")
- }
- else
- {
- println("The List is not empty")
- }
To insert an item into the array at a specified index, call the array's insert method: shoppingList.insert ("syrup", atIndex : 0). This call to insert method inserts a new item with a value of "syrup" at the beginning of the list and it is indicated by an index of 0. The removeAtIndex method is used to remove an item from the array and returns the removed item. To remove the final item in the array, the removeLast method rather than the removeAtIndex method to avoid the need to query the array count property.

Join the conversation! Your thoughts help the community grow.