An array in swift is written as ** Array <Element> **, where Element is the type of values โโthat the array can be stored.
The array can be initialized as:
let emptyArray = [String]()
It shows that its array is a string of type
The variable type emptyArray is defined as [String] from the type of the initializer.
To create an array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
The groceryList file was initialized with two items.
The groceryList variable is declared as an "array of string values written as [String]. This particular array specified the type of the String value, it is only allowed to store String values.
There are various array properties like:
- check if there is an array of elements (if the array is empty or not)
isEmpty property (Boolean) to check if the count property is 0:
if groceryList.isEmpty { print("The groceryList list is empty.") } else { print("The groceryList is not empty.") }
- Adding (adding) elements to the array
You can add a new element to the end of the array by calling the arrays append (_ :) method:
groceryList.append("Flour")
The gcceryList file now contains 3 elements.
Alternatively, add an array of one or more compatible elements with the add assignment operator (+ =):
groceryList += ["Baking Powder"]
The groceryList file now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
The gcceryList file now contains 7 elements