Arrays in Swift: 5 Fatal Errors When Adding Elements (and How to Avoid Them)

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Even append Can Break Your Code?

\n\n

It would seem that nothing could be simpler than adding an element to an array in Swift. You write array.append(newElement) — and it's done. However, judging by the thousands of views on Stack Overflow, this seemingly trivial operation stumps both beginners and experienced developers.

\n\n

In this article, we won't just show you how to add an element to an array in Swift. We'll break down 5 of the most common and insidious errors that turn a simple append into a headache. You'll learn why the compiler might complain about seemingly correct code, how to avoid going out of bounds of an array, and what the difference is between append and insert. Let's go!

\n\n

Error #1: Forgetting About Strict Typing

\n\n

Swift is a strictly typed language. This means an array declared as [Int] will not accept a string, even if it looks a lot like a number. This is a common pitfall for those coming from Python or JavaScript.

\n\n

The Problem: Type Mismatch

\n\n
var numbers: [Int] = [1, 2, 3]\n// Compilation error: Cannot convert value of type 'String' to expected argument type 'Int'\nnumbers.append("4")\n
\n\n

The Solution: Type Casting

\n\n

Always explicitly cast data to the array's type. Use initializers or explicit conversion:

\n\n
var numbers: [Int] = [1, 2, 3]\nif let intValue = Int("4") {\n    numbers.append(intValue) // ✅ Works: numbers = [1, 2, 3, 4]\n}\n\n// Or for a string array:\nvar strings: [String] = ["a", "b"]\nstrings.append(String(42)) // ✅ "42" added as a string\n
\n\n

Tip: If you are adding elements from an external source (API, user input), always check the type with as? or use compactMap to filter out nil.

\n\n

Error #2: Index out of range When Using insert

\n\n

The insert(_:at:) method allows you to insert an element at an arbitrary position. But if you specify an index that is greater than the number of elements in the array, the application will crash with a Fatal error: Index out of range.

\n\n

The Problem: Inserting Outside the Array Bounds

\n\n
var fruits = ["Apple", "Banana"]\n// Array of 2 elements: indices 0 and 1\n// Error! Index 5 does not exist\nfruits.insert("Orange", at: 5)\n
\n\n

The Solution: Bounds Checking and Safe Extension

\n\n

There are two ways to avoid this error:

\n
    \n
  • Index checking: Ensure the index is in the range from 0 to array.count (inclusive for insert).
  • \n
  • Automatic appending: If you want to insert an element at the end when it's out of bounds, use logic with append.
  • \n
\n\n
var fruits = ["Apple", "Banana"]\n\n// Safe option 1: check\nlet index = 5\nif index >= 0 && index <= fruits.count {\n    fruits.insert("Orange", at: index)\n} else {\n    // If the index is greater than count, simply append to the end\n    fruits.append("Orange")\n}\nprint(fruits) // ["Apple", "Banana", "Orange"]\n\n// Safe option 2: extension\nextension Array {\n    mutating func safeInsert(_ element: Element, at index: Int) {\n        if index >= 0 && index <= self.count {\n            self.insert(element, at: index)\n        } else {\n            self.append(element)\n        }\n    }\n}\n\nfruits.safeInsert("Kiwi", at: 100) // ✅ Will add to the end\n
\n\n

Error #3: Confusion Between append and +=

\n\n

The += operator can also add elements, but its behavior differs from append. The main difference: += works with collections, not with single elements.

\n\n

The Problem: Implicit Array Creation

\n\n
var list = [1, 2, 3]\nlis                

Blogs

Book Recommendations