Variables

Arrays in Swift

Arrays are used to assign a series of elements of the same type in consecutive memory locations; to define a list of elements. They work similar to variables, except they contain multiple values at different indices.


Syntax
//empty array
var arrayName = [dataType]()
arrayName.append(value) //add item to array
arrayName += [value] //another way of adding an item

arrayName[index] //access array value

//array with default values
var defaultArray = [dataType](count: countNumber, repeatedValue: valueToRepeat)

//array with pre-defined values
var predefinedArray: [dataType] = [value1, value2, ...]

Notes

The range of array indices is 0 to size minus 1. The size of an array can be found using the .count property.

Arrays can be added together. They can also be made empty again using [].

You can check if an array is empty by using the .isEmpty property.


Example
var array = [int]() //declaring an array of size 2 
array.append(0) //storing a value of 1 in the first element
array += 1 //storing a value of 2 in the second element

< Optionals   |   Dictionaries >

© 2019 SyntaxDB. All Rights Reserved.