Swift Language Arrays Basics of Arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Array is an ordered collection type in the Swift standard library. It provides O(1) random access and dynamic reallocation. Array is a generic type, so the type of values it contains are known at compile time.

As Array is a value type, its mutability is defined by whether it is annotated as a var (mutable) or let (immutable).

The type [Int] (meaning: an array containing Ints) is syntactic sugar for Array<T>.

Read more about arrays in The Swift Programming Language.

Empty arrays

The following three declarations are equivalent:

// A mutable array of Strings, initially empty.

var arrayOfStrings: [String] = []      // type annotation + array literal
var arrayOfStrings = [String]()        // invoking the [String] initializer
var arrayOfStrings = Array<String>()   // without syntactic sugar

Array literals

An array literal is written with square brackets surrounding comma-separated elements:

// Create an immutable array of type [Int] containing 2, 4, and 7
let arrayOfInts = [2, 4, 7]

The compiler can usually infer the type of an array based on the elements in the literal, but explicit type annotations can override the default:

let arrayOfUInt8s: [UInt8] = [2, 4, 7]   // type annotation on the variable
let arrayOfUInt8s = [2, 4, 7] as [UInt8] // type annotation on the initializer expression
let arrayOfUInt8s = [2 as UInt8, 4, 7]   // explicit for one element, inferred for the others

Arrays with repeated values

// An immutable array of type [String], containing ["Example", "Example", "Example"]
let arrayOfStrings = Array(repeating: "Example",count: 3)

Creating arrays from other sequences

let dictionary = ["foo" : 4, "bar" : 6]

// An immutable array of type [(String, Int)], containing [("bar", 6), ("foo", 4)]
let arrayOfKeyValuePairs = Array(dictionary)

Multi-dimensional arrays

In Swift, a multidimensional array is created by nesting arrays: a 2-dimensional array of Int is [[Int]] (or Array<Array<Int>>).

let array2x3 = [
    [1, 2, 3],
    [4, 5, 6]
]
// array2x3[0][1] is 2, and array2x3[1][2] is 6.

To create a multidimensional array of repeated values, use nested calls of the array initializer:

var array3x4x5 = Array(repeating: Array(repeating: Array(repeating: 0,count: 5),count: 4),count: 3)


Got any Swift Language Question?