Basic Array Operations
Count
The length of your array is accessible through the count field. To access it, just do myArray.count
.
Get
Getting a single element is standard–it's your array followed by square brackets that contain the index of the element you want. Of course, make sure it is within the bounds of the array or else you will have a runtime error. Lists are 0-indexed meaning that the bounds for any list is 0 to one less than the length of the list.
If you want to get a section of the array, or an ArraySlice
, you need to use ranges. See the ranges page for their construction.
This range must correspond to indices that will be used in the array slice.
The section you specify will be used to create a new ArraySlice
, which contains the information with limited functionality of arrays. To get this functionality back use the the Array(_: Sequence)
initializer to convert back to an array.
There are two more ways to get elements from an array, which are more advanced because they require an understanding of anonymous functions and optionals.
Put
We use subscript assignments to assign elements to pre-existing locations.
To add a new element at the end of a list, or to add a new element when order does not matter, use the append(_: element)
method.
To add an element at a specific location, we use the insert(_: element, at: Int)
method. This method will shift every element after this location up by one, and then insert the element at the location:
Removal
To remove an element at a specific location use remove(at: Int)
.
Addition
What do you do if you have two lists that you want to concatenate? One technique would be sequentially appending them–iterate through one list and sequentially add the elements of the list to the other list. Another, more efficient and clean way is just to use the +
operator.
Last updated