Swift Integer Array

A Swift integer array is an ordered collection whose elements are all values of type Int. Swift writes this type as [Int], which is shorthand for Array<Int>. Array indexes start at 0, and the array can grow or shrink when it is declared with var.

This tutorial explains how to create an empty integer array, initialize an array with values, create an array of a specific size, access and update elements, add and remove integers, iterate through the array, and avoid invalid-index errors.

Create an Empty Swift Integer Array

To create an empty Integer array, use the following syntax.

</>
Copy
var array_name = [Int]()

array_name is an identifier used to access the integer array. The [Int] type specifies that every element stored in the array must be an integer.

You do not specify a fixed capacity when creating a normal Swift array. The initial count of an empty array is 0.

An empty integer array can also be declared with an explicit type and an empty array literal:

</>
Copy
var numbers: [Int] = []

Use var when the array will be modified. Use let when its elements and size should remain unchanged after initialization.

Create a Swift Integer Array with a Repeated Default Value

Swift can create an integer array containing a specified number of repeated values. The following syntax is found in older Swift code:

</>
Copy
var array_name = [Int](count: array_size, repeatedValue: default_value)

In this legacy syntax, array_size defines the number of elements and default_value is assigned to each element.

An example would be

</>
Copy
var numbers = [Int](count: 3, repeatedValue: 10)

The array represented by the statement contains three integers, with each element initialized to 10.

In current Swift, use the Array(repeating:count:) initializer:

</>
Copy
var numbers = Array(repeating: 10, count: 3)
print(numbers)

Output

[10, 10, 10]

The count argument must be zero or greater. This initializer is useful when you need an integer array of a known initial length, such as counters, scores, or placeholder values.

Create a Swift Integer Array with Initial Values

You can declare and initialize an integer array in one statement by placing comma-separated values inside square brackets.

</>
Copy
var array_name:[Int] = [7, 54, 21]

The type annotation [Int] appears after the variable name, and the initial integer values appear on the right side.

Swift can also infer the element type from an integer array literal:

</>
Copy
let primeNumbers = [2, 3, 5, 7, 11]

Here, Swift infers primeNumbers as [Int]. An integer literal may also be inferred as another numeric type when an explicit contextual type is supplied, so add : [Int] when the intended type should be clear.

Create an Integer Array from a Swift Range

Use the Array initializer to convert an integer range into an array. A closed range includes both endpoints:

</>
Copy
let numbers = Array(1...5)
print(numbers)

Output

[1, 2, 3, 4, 5]

For a zero-based sequence containing five elements, use Array(0..<5), which produces [0, 1, 2, 3, 4].

Access Swift Integer Array Elements by Index

Use subscript syntax to access an element at a specific index.

main.swift

</>
Copy
var numbers:[Int] = [7, 54, 21]

var a = numbers[1]

print( "Value of integer at index 1 is \(a)" )

Output

Value of element at index 1 is 54

Note: Swift array indexes start at 0. For the array above, numbers[0] is 7, numbers[1] is 54, and numbers[2] is 21.

Accessing an index that is outside the valid range causes a runtime error. Check the array’s indices collection before using an index that comes from user input or another external source:

</>
Copy
let numbers = [7, 54, 21]
let requestedIndex = 2

if numbers.indices.contains(requestedIndex) {
    print(numbers[requestedIndex])
} else {
    print("Index is out of range")
}

Read the First and Last Integer Safely

The first and last properties return optional values. They return nil when the array is empty, so they are safer than directly subscripting an array whose state is unknown.

</>
Copy
let numbers = [7, 54, 21]

if let firstNumber = numbers.first {
    print("First: \(firstNumber)")
}

if let lastNumber = numbers.last {
    print("Last: \(lastNumber)")
}

Update an Integer at a Swift Array Index

An array declared with var can be updated by assigning a new integer to a valid index.

</>
Copy
var numbers = [7, 54, 21]
numbers[1] = 60

print(numbers)

Output

[7, 60, 21]

Append, Insert, and Remove Integers in a Swift Array

Use append(_:) to add an integer at the end, insert(_:at:) to add one at a valid position, and a removal method such as remove(at:) or removeLast() to delete an element.

</>
Copy
var numbers = [10, 20, 30]

numbers.append(40)
numbers.insert(15, at: 1)
let removedNumber = numbers.remove(at: 2)

print(numbers)
print("Removed: \(removedNumber)")

Output

[10, 15, 30, 40]
Removed: 20

Before calling removeLast(), confirm that the array is not empty. Before calling remove(at:), confirm that the specified index is valid.

Check Swift Integer Array Count and Empty State

Use count to read the number of integers and isEmpty to determine whether the array contains any elements.

</>
Copy
let numbers = [4, 8, 12]

print(numbers.count)
print(numbers.isEmpty)

Output

3
false

Find an Integer and Its Index in a Swift Array

Use contains(_:) to test whether an integer exists. Use firstIndex(of:) when you also need the index of its first occurrence.

</>
Copy
let numbers = [10, 20, 30, 20]

print(numbers.contains(30))

if let index = numbers.firstIndex(of: 20) {
    print("First 20 is at index \(index)")
}

Output

true
First 20 is at index 1

Loop Through Integers and Array Indexes in Swift

A for-in loop reads each integer in order. Use enumerated() when both the offset and value are needed.

</>
Copy
let numbers = [7, 54, 21]

for number in numbers {
    print(number)
}

for (index, number) in numbers.enumerated() {
    print("Index \(index): \(number)")
}

Common Swift Integer Array Operations

The following tutorials cover related array operations:

Swift Integer Array Errors to Avoid

  • Using an invalid index: valid indexes run from startIndex up to, but not including, endIndex.
  • Modifying a constant array: an array declared with let cannot be changed.
  • Mixing incompatible element types: a [Int] array accepts only Int values unless values are explicitly converted.
  • Using legacy repeated-value syntax: current Swift uses Array(repeating:count:), not the older repeatedValue label.
  • Removing from an empty array: check isEmpty before calling methods that require an existing element.

Swift Integer Array FAQs

What is an integer array in Swift?

An integer array is an ordered collection of Int values. Its type can be written as [Int] or Array<Int>.

How do I create an empty integer array in Swift?

Use var numbers: [Int] = [] or var numbers = [Int](). Both declarations create an empty mutable integer array.

How do I create a Swift integer array of a specific size?

Use Array(repeating: initialValue, count: size). For example, Array(repeating: 0, count: 5) creates five integer elements initialized to zero.

How do I access a Swift array element without an index error?

Check numbers.indices.contains(index) before subscripting. For the first or last element, use the optional first and last properties.

How do I get the length of an integer array in Swift?

Use the array’s count property. For example, numbers.count returns the number of integers currently stored in the array.

Swift Integer Array QA Checklist

  • Confirm every declaration intended to store integers is typed or inferred as [Int].
  • Confirm new repeated-value examples use Array(repeating:count:).
  • Verify every subscript uses an index contained in the array’s indices.
  • Check that mutation examples declare the array with var, not let.
  • Run each example and verify that its displayed output matches the code.

Swift Integer Array Summary

Swift represents an integer array with [Int]. You can create one with an empty literal, an array literal, a range, or Array(repeating:count:). Use zero-based subscripts for valid indexes, count and isEmpty for inspection, and array methods to add, find, update, or remove values. For more Swift examples, see this Swift Tutorial.