A big limitation of static arrays in Swift is the fact that once the array is created, it has a fixed size.
The Array declared with var overcomes this limitation by having variable size and allowing for elements to be added or removed.
Creation:
We create an empty Array by specifying the type of the elements inside [] followed by parenthesis:
[String]()
This code creates an empty Array where each item is a String.
Type Annotation:
A good practice is to annotate the type of the created Array by specifying the element type in the variable declaration, like this:
var sandwich: [String] = []
Initialization:
You can also initialize an Array at creation by using an array literal and put a comma between each entry, like this:
var sandwich: [String] = [
"peanut butter", "jelly", "bread"
]
We created an Array named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".
Assignment
Follow the Coding Tutorial and let's create some Arrays!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.