Arrays in Swift

Our first example demonstrates the use of arrays in Swift. An array is an ordered collection of elements of the same type.

import Foundation

// Here we create an array `a` that will hold exactly 5 Ints.
// By default, an array is initialized with the specified number of elements set to the default value of its type.
var a = Array(repeating: 0, count: 5)
print("emp:", a)

// We can set a value at an index using subscript syntax, and get a value with the same syntax.
a[4] = 100
print("set:", a)
print("get:", a[4])

// The count property returns the length of an array.
print("len:", a.count)

// Use this syntax to declare and initialize an array in one line.
let b = [1, 2, 3, 4, 5]
print("dcl:", b)

// In Swift, arrays are dynamic and can grow or shrink. Here's how you can add elements:
var c = [1, 2, 3, 4, 5]
c.append(6)
print("append:", c)

// You can also initialize an array with specific indices
var d = [Int](repeating: 0, count: 5)
d[0] = 100
d[3] = 400
d[4] = 500
print("idx:", d)

// Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.
var twoD = [[Int]](repeating: [Int](repeating: 0, count: 3), count: 2)
for i in 0..<2 {
    for j in 0..<3 {
        twoD[i][j] = i + j
    }
}
print("2d:", twoD)

// You can create and initialize multi-dimensional arrays at once too.
twoD = [
    [1, 2, 3],
    [4, 5, 6]
]
print("2d:", twoD)

Note that arrays appear in the form [v1, v2, v3, ...] when printed with print().

When you run this program, you’ll see output similar to:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
append: [1, 2, 3, 4, 5, 6]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

This example demonstrates various ways to create, initialize, and work with arrays in Swift. Unlike some languages, Swift arrays are type-safe and always clear about the types of values they can store. They can be one-dimensional or multi-dimensional, and can grow dynamically when needed.