HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to SwiftVariablesData TypesOperatorsStringsArraysConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Array & Dictionary
🔀 Condition & Loop
🧩 Function
Swift›Arrays

Arrays

Array creation, element access, adding (append), count, and iterating with loops.

Simple enough for a 5-year-old to understand

Create an array and access elements

Arrays hold ordered values. The index starts at 0.

Example code
1
let languages = ["Swift", "Go", "Rust"]
An array with three elements.
VariableAn array with three elements.
2
print(languages[0])
Swift (first element)
Output / InputSwift (first element)
3
print(languages.count)
3 (number of elements)
Output / Input3 (number of elements)
4
print(languages)
["Swift", "Go", "Rust"]
Output / Input["Swift", "Go", "Rust"]
VariableOutput / Input
💡 Hint: Number of elements .count, first element arr[0].

About this topic

An array is a collection that stores multiple values of the same type in an ordered manner. In Swift, the type of an array is determined by the type of its elements: [Int] is an array of integers, and [String] is an array of strings. You cannot put different types into the same array.

Arrays are zero-indexed, and going out of bounds will crash the app at runtime. This is a deliberate design choice in Swift: instead of silently returning an empty value, it makes the error immediately visible.

An important detail: in Swift, an array is a value type. When you assign an array to another variable, it gets copied; modifying one does not affect the other. This behavior might be surprising to those coming from reference-type languages, but it prevents a vast number of bugs.

What you will learn

  • Creating arrays and accessing elements
  • Adding and removing elements
  • Iterating over an array
  • The outcome of out-of-bounds access
  • What it means for an array to be a value type

Who is this for?

  • Those who will store data in a list format
  • Developers who will process records coming from a server
  • Those who want to learn the difference between reference and value types

When to use?

Behind table and list screens, there is almost always an array; the number of rows is the number of elements in the array.

For data where order doesn't matter and duplicates aren't allowed, a Set is more appropriate; for key-value mappings, a Dictionary is better.

Common mistakes

Wrong

let names = ["Alice", "Ayse"]
print(names[5])

The array only has indices 0 and 1; when index 5 is requested, the app crashes with "Fatal error: Index out of range". Swift does not return nil in this case. For safe access, you should check the index first or work with indices.

Correct

let names = ["Alice", "Ayse"]
if names.indices.contains(5) {
  print(names[5])
} else {
  print("no such element")
}

Wrong

let numbers = [1, 2, 3]
numbers.append(4)

Since the array is defined with let, its contents cannot be modified either; you get a "cannot use mutating member on immutable value" error. In Swift, collection immutability stems from the definition itself, no separate flag is needed. If you are going to add elements, you must use var.

Correct

var numbers = [1, 2, 3]
numbers.append(4)

Wrong

var a = [1, 2, 3]
var b = a
b.append(4)
print(a.count)

There is no error here, but the expectation might be wrong: a still has 3 elements. Swift arrays are value types, assignment produces a copy. Those coming from reference-type languages expect 4 here, and the result surprises them. If you want a shared mutable structure, you need to use a class.

Correct

var a = [1, 2, 3]
a.append(4)
print(a.count)

Frequently asked questions

How do I find out the array length?

The count property gives the number of elements. To check if an array is empty, using isEmpty instead of count == 0 is both more readable and faster for some collection types.

Why do first and last return an Optional?

Because the array might be empty, and in that case there is no such thing as a first element. Swift expresses this with nil, so instead of crashing on an empty array, you get a manageable value. This is the safe way, unlike subscript access.

Can I delete elements while iterating over an array?

You should not; loop indices will shift and some elements will be skipped. The correct way is to create a new array using filter containing the elements not to be deleted, or to use removeAll(where:).

Summary

An array is homogeneous and ordered, and it is zero-indexed.

Out-of-bounds access crashes the app.

An array defined with let cannot be mutated.

An array is a value type; assignment produces a copy.

first and last return an Optional in case the array is empty.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code