Start learning free

LESSON 93 OF 415 · ARRAYS I

Static Arrays in Swift: Creating Fixed-Size Arrays

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In Swift, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

Swift has no separate fixed-size array type. We create an array with a set number of items by specifying the element type and a repeating initial value (a let array can never change size):

let arrayOfStrings = [String](repeating: "", count: 3)

In this program we created an array named arrayOfStrings that consists of 3 String items.

These 3 items are "" (empty string, no value given yet) initially.


Creation & Initialization:

There is a way to initialize an array at creation by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

var arrayOfStrings = ["AlgoCademy", "coding", "static arrays"]

We created an array named arrayOfStrings which consists of 3 String items: "AlgoCademy", "coding" and "static arrays".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · ARRAYS I

    Static Arrays in Swift, explained

    What an array is

    An array stores several values of the same type in one ordered collection. Instead of declaring fruit1, fruit2 and fruit3, you declare one array and reach each value by its position. Every element has the same type: an array of String can't also hold an Int.

    A static (or fixed) array is one whose length is decided when it is created and doesn't change afterwards. Swift has a single array type, Array, written [Element]. Whether an array behaves as a fixed one depends on how you declare it and what you do with it: a let array can never change at all, and a var array stays fixed as long as you never add or remove elements. The next lesson covers arrays that grow.

    Two ways to create an array

    Repeating one value

    When you know how many slots you need but not yet what goes in them, fill the array with a repeated value:

    var arrayOfStrings = [String](repeating: "", count: 3)
    print(arrayOfStrings)        // ["", "", ""]
    print(arrayOfStrings.count)  // 3
    

    [String] names the type, repeating: is the value placed in every slot and count: is how many slots there are. You can also write Array(repeating: 0, count: 20) and let Swift infer the element type from the value: here it is Int, so the result is [Int]. The argument labels repeating: and count: are required, in that order.

    Listing the values

    When you know the values, write them in an array literal: square brackets with the items separated by commas.

    let fruits = ["mango", "kiwi", "grapefruit"]
    print(fruits)  // ["mango", "kiwi", "grapefruit"]
    

    Swift looks at the values and infers the type [String], so no annotation is needed. If the literal mixes unrelated types, such as [14, "thirty"], the compiler can't pick one element type and reports an error.

    let or var

    Both declarations create the array, but they differ in what you may do afterwards. Assigning to an element of a let array is a compile error:

    let fruits = ["mango", "kiwi", "grapefruit"]
    fruits[0] = "apple"
    

    The compiler reports cannot assign through subscript: 'fruits' is a 'let' constant. Declare the array with var when its elements need to change. Prefer let whenever they don't, because it makes the intent clear and the compiler enforces it.

    The exercise, step by step

    1. Create numbers. The task asks for a constant array of 20 integers, all zero. A constant means let, and the zero-filled array comes from Array(repeating:count:) with the value 0 and a count of 20. The element type is Int, inferred from the 0.
    2. Create fruits. Use let and an array literal with "mango", "kiwi" and "grapefruit", in that order. The strings are written with double quotes.
    let numbers = Array(repeating: 0, count: 20)
    let fruits = ["mango", "kiwi", "grapefruit"]
    

    Checking the result: numbers.count is 20, and numbers[19], the last slot, is 0.

    Common mistakes

    • Leaving out the labels. Array(0, 20) doesn't compile. Swift needs repeating: and count:.
    • Mixing up the arguments. Array(repeating: 20, count: 0) is a valid call, but it makes an empty array. The value comes first and the count second.
    • Using single quotes. 'mango' is not a Swift string. Strings use double quotes.
    • Mixing element types. An array of strings can't hold the number 5. When the types differ, the compiler reports an error instead of converting.
    • Assuming let only protects the name. With a let array, the contents are frozen too. Arrays in Swift are values, so there is no way to change a constant array through its name.

    Key takeaways

    • An array holds values of one type, in order.
    • Array(repeating:count:) builds an array of a given size filled with one value.
    • An array literal lists the values directly and lets Swift infer the type.
    • Use let for an array that never changes and var for one that does.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free