> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Array

An `Array` in Swift is a generic, ordered, random-access collection that stores elements of a single, uniform type. Implemented as a value type (`struct`) in the Swift Standard Library, it utilizes a copy-on-write (CoW) mechanism to optimize performance during assignment and mutation. While an `Array` typically stores its elements in a contiguous memory block, it does not strictly guarantee contiguous storage if it is bridged to an Objective-C `NSArray`.

## Type Declaration and Syntax

Swift provides both a formal generic syntax and a syntactic sugar shorthand for declaring arrays. The shorthand is the idiomatic standard.

```swift theme={"dark"}
// Formal generic syntax
var formalArray: Array<Int>

// Shorthand syntax (preferred)
var shorthandArray: [Int]
```

## Initialization

Arrays can be instantiated using empty initializers, array literals, or specialized initializers for pre-allocating repeated values.

```swift theme={"dark"}
// Empty initialization
let emptyArray: [String] = []
let anotherEmptyArray = [String]()

// Array literal initialization (type inferred as [Int])
let literalArray = [1, 2, 3, 4, 5]

// Repeating value initialization
let repeatingArray = Array(repeating: 0.0, count: 5) // [0.0, 0.0, 0.0, 0.0, 0.0]
```

## State Inspection and Iteration

The `Array` type provides constant-time property access to check its current state and size, alongside standard sequence iteration.

```swift theme={"dark"}
let numbers = [10, 20, 30]

// State inspection
let size = numbers.count      // 3
let isArrayEmpty = numbers.isEmpty // false

// Standard iteration
for number in numbers {
    print(number)
}

// Iteration with index
for (index, number) in numbers.enumerated() {
    print("Index: \(index), Value: \(number)")
}
```

## Memory and Performance Characteristics

* **Value Semantics:** Because `Array` is a struct, assigning an array to a new variable or passing it to a function creates a logically distinct instance.
* **Copy-on-Write (CoW):** To minimize memory overhead, Swift arrays share the same underlying memory buffer upon assignment. A physical copy of the buffer is only allocated in memory at the exact moment one of the references mutates the array.
* **Capacity and Reallocation:** Arrays allocate a specific amount of memory to store elements. When an array exceeds its `capacity`, it allocates a larger memory buffer and copies the existing elements over. This reallocation strategy ensures that appending elements operates in amortized `O(1)` time.
* **Bridging and Contiguity:** Swift `Array` bridges seamlessly to Foundation's `NSArray`. If the array contains class types or `@objc` protocols, it may be backed by an `NSArray` instance, which does not guarantee contiguous memory. For scenarios requiring strict contiguous memory allocation (such as interfacing with C APIs), Swift provides the `ContiguousArray` type.

## Slicing and Memory Management

Extracting a subrange of an array returns an `ArraySlice` rather than a new `Array`.

```swift theme={"dark"}
let originalArray = [10, 20, 30, 40, 50]
let slice = originalArray[1...3] // Type is ArraySlice<Int>
```

An `ArraySlice` presents a view into the original array and shares its underlying memory buffer. This makes slicing an `O(1)` operation. However, because the slice holds a strong reference to the entire original buffer, keeping a long-lived reference to a small slice will prevent the original, potentially large array from being deallocated, resulting in prolonged memory retention (or memory bloat). This is not a memory leak, as the memory is safely tracked by Automatic Reference Counting (ARC) and will be properly deallocated once the slice goes out of scope. However, to allow the original buffer to be freed immediately when it is no longer needed, the slice must be explicitly converted into a new, independent array:

```swift theme={"dark"}
// Allocates a new buffer and copies the elements, allowing originalArray to be deallocated
let independentArray = Array(slice) 
```

## Protocol Conformance

The behavior of `Array` is defined by its conformance to several key Swift protocols:

* `RandomAccessCollection`: Guarantees `O(1)` time complexity for index-based element access and distance calculations.
* `MutableCollection`: Permits in-place element mutation via subscripting.
* `RangeReplaceableCollection`: Supports replacing arbitrary subranges of elements, appending, inserting, and removing.
* `ExpressibleByArrayLiteral`: Enables instantiation using the `[value1, value2]` literal syntax.

## Structural Operations

Array operations are strictly bound by index bounds checking. Accessing an index outside the range of `0..<count` triggers a runtime trap.

```swift theme={"dark"}
var numbers = [10, 20, 30]

// Subscript access and mutation: O(1)
let firstElement = numbers[0]
numbers[1] = 25 

// Appending elements: Amortized O(1)
numbers.append(40)
numbers.append(contentsOf: [50, 60])
numbers += [70, 80]

// Insertion and Removal: O(n) due to shifting subsequent elements
numbers.insert(15, at: 1)
let removedElement = numbers.remove(at: 2)

// Capacity management
numbers.reserveCapacity(100) // Pre-allocates memory to prevent reallocation overhead
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
