Skip to main content

Command Palette

Search for a command to run...

Data Structures In Swift: Fixed-Size Arrays

How to create a fixed-size array using Swift

Updated
2 min read
Data Structures In Swift: Fixed-Size Arrays

What Is It?

A fixed-size array is a data structure that assigns a fixed, contiguous amount of memory to store a set amount of elements. Each element is assigned to an index beginning at 0 and counting up to the total amount. For example, creating an array of 10 elements has an index counting from 0 to 9 (10 total indices).

The amount of indices, and therefore elements, can't be changed after the array is created. Each element in the array can be accessed and modified by its index, and the total capacity is set and constant throughout its lifetime.

How do we create one?

Below is a simple implementation of a fixed-size array using Swift:

// CREATING FIXED-SIZE ARRAYS

import Foundation

// Create an array struct that accepts various types
struct FixedSizeArray<T> {

    // Store maximum size as an integer
    private var maxSize: Int

    // Store a default value type
    private var defaultValue: T

    // Store array property as type T
    private var array: [T]

    // Store a count of array elements
    private(set) var count = 0

    // Initialize array with maxSize & defaultValue
    init(maxSize: Int, defaultValue: T) {
        self.maxSize = maxSize // Set maximum size
        self.defaultValue = defaultValue // Set default values
        // Create the array with above properties
        self.array = Array(repeating: defaultValue, count: maxSize)
    }

    // Compute the count
    subscript(index: Int) -> T {
        precondition(index >= 0 && index < count, "Index out of bounds")
        return array[index]
    }

    // Append item after count & increment count
    mutating func append(_ newElement: T) {
        precondition(count < maxSize, "Array is full")
        array[count] = newElement
        count += 1
    }

    // Remove item at index & set index to default value
    mutating func remove(at index: Int) -> T {
        precondition(index >= 0 && index < count, "Index out of bounds")
        count -= 1
        let result = array[index]
        array[index] = array[count]
        array[count] = defaultValue
        return result
    }

    // Replace all values with defaultValue & reset count
    mutating func removeAll() {
        array.replaceSubrange(0..<count, with: Array(repeating: defaultValue, count: count))
        count = 0
    }
}

// Create an array by passing in a maxSize & defaultValue
var array = FixedSizeArray(maxSize: 12, defaultValue: 0)

Now, let's fiddle with the array a bit.

// View and make changes to the array
print(array)
array.append(1)
array.append(2)
array.append(3)
array.append(4)
print(array)
array.remove(at: 3)
print(array)
array.removeAll()
print(array)

Conclusion

Fixed-size arrays are still a very useful data structure in programming. For a deeper dive into them, check out how they are implemented in C. Next, I'll be taking a look at how to create the more commonly used arrays, which can dynamically increase and decrease in size.

Programming

Part 11 of 17

Articles and tutorials about programming and computer science concepts.

Up next

Algorithms In Swift: Stacks

How to create a stack using Swift

More from this blog

Damian Robinson | Online

20 posts

The blog and business site of Damian Robinson. You will find tutorials about programming and cybersecurity, and articles pertaining to various interests or pursuits of the author.