Swift Introduction | Arrays and Dictionaries | Array Basics

An array manages multiple values together. It stores values of the same type and assigns each storage location an index starting at 0. Use an index to retrieve or replace a value.

An array is created with a specified number of storage locations. An array with ten elements has indexes from 0 through 9, not 1 through 10. Reading or writing an index outside the allocated range causes an error.

Creating Arrays

var variable:Type = [Type]()
var variable:Type = [Type](count: number, repeatedValue: value)
var variable:Type = [value1, value2, ...]

Reading and Writing Values

variable = array[index]
array[index] = value

Write the element type inside square brackets. For example, an array of strings has the type [String].

Create an empty array with [Type](). To create storage locations with an initial value, write:

[Type](count: numberOfLocations, repeatedValue: initialValue)

You can also use an array literal such as [value1, value2, ...].

var arr1 : [Int] = [Int] (count : 10, repeatedValue : 0)
var arr2 : [Int] = [0,0,0,0,0,0,0,0,0,0]

An array literal is convenient for a small number of elements. For ten thousand zero values, (count: 10000, repeatedValue: 0) is more practical.

Swift can infer the type when the assigned value makes it clear.

var arr1 = [Int] (count : 10, repeatedValue : 0)
var arr2 = [0,0,0,0,0,0,0,0,0,0]