Swift
Empty Array
Swift Programming
iOS Development
Swift Tips

How to create an empty array in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating an empty array in Swift is simple, but the exact syntax depends on whether the compiler can infer the element type. Since Swift arrays are strongly typed, an empty literal by itself is often not enough. The important part is making the array type explicit when the surrounding context does not provide it.

The Two Standard Forms

Swift supports two common ways to create an empty array. Both create the same underlying type.

swift
1var numbers: [Int] = []
2var moreNumbers = [Int]()
3
4print(numbers.isEmpty)
5print(moreNumbers.count)

The first form uses an empty literal with a type annotation. The second calls the array initializer directly. Use whichever is clearer in the surrounding code.

Why Type Information Matters

An empty literal has no elements, so Swift cannot infer the element type unless context already exists.

This fails:

swift
// var items = []   // Error: empty collection literal requires an explicit type

This succeeds because the type is known:

swift
let items: [String] = []
print(items)

The rule is straightforward: if there are no elements, you must tell Swift what kind of array you want.

Mutable Versus Immutable Empty Arrays

Use var if you plan to append values later. Use let if the array should stay fixed after creation.

swift
1var queue: [String] = []
2queue.append("job-1")
3queue.append("job-2")
4print(queue)
5
6let constants: [Int] = []
7print(constants.isEmpty)

Trying to modify an array declared with let is a compile-time error, which is useful when immutability is part of the design.

Type Inference from Function Parameters

Sometimes you do not need an explicit type because the function signature supplies it.

swift
1func process(names: [String]) {
2    print("received \(names.count) names")
3}
4
5process(names: [])

Here, the compiler sees that process expects [String], so the empty literal is accepted. This is why [] sometimes works and sometimes does not.

Arrays of Custom Types

The same syntax works for structs, classes, and enums.

swift
1struct User {
2    let id: Int
3    let name: String
4}
5
6var users: [User] = []
7users.append(User(id: 1, name: "Ava"))
8print(users.count)

This becomes common in view models, network layers, and list-based UI code where the array starts empty and is filled after loading data.

Reserving Capacity for Performance

Creating an empty array does not preallocate room for many future elements. If you know roughly how many values will be appended, reserve capacity up front to reduce reallocations.

swift
1var ids: [Int] = []
2ids.reserveCapacity(1000)
3
4for i in 0..<1000 {
5    ids.append(i)
6}
7
8print(ids.count)

You should not do this blindly, but it is useful in performance-sensitive code paths such as parsing or batch processing.

Nested and Optional Arrays

Empty arrays also show up in more complex types. A nested array still needs a full type annotation.

swift
let matrix: [[Int]] = []
print(matrix)

An optional array is different from an empty array:

swift
1var a: [Int]? = nil
2var b: [Int] = []
3
4print(a == nil)     // true
5print(b.isEmpty)    // true

nil means “no array exists.” An empty array means “the array exists, but it contains zero elements.” That distinction matters in API design and decoding logic.

Array Literals Versus Other Collection Types

Do not confuse empty arrays with empty sets or dictionaries. Swift uses different syntax for each collection type.

swift
1let array: [Int] = []
2let dictionary: [String: Int] = [:]
3let set: Set<Int> = []
4
5print(array.count, dictionary.count, set.count)

The empty array literal is [], while the empty dictionary literal is [:]. That difference is easy to miss when moving quickly.

Practical Guidance

In most app code, var items: [Model] = [] is the clearest choice. It communicates both the type and the initial state in one line. Array<Model>() is equally correct, but teams often reserve it for generic code or when initializer style fits better with nearby declarations.

If a property will start empty and be populated later, prefer making it non-optional unless nil carries distinct meaning. That keeps downstream code simpler because callers can check isEmpty instead of unwrapping first.

Common Pitfalls

The main mistake is declaring var items = [] and expecting Swift to infer the type. Another common issue is using nil when an empty array would be clearer and easier to handle. Developers also sometimes choose let and then forget they plan to append values later. In performance-heavy code, repeatedly growing a large array without reserving capacity can add unnecessary overhead.

Summary

  • Create an empty Swift array with [] plus a type annotation or with Array<Element>().
  • Swift needs explicit type information when the array has no elements.
  • Use var for arrays you will modify and let for fixed values.
  • Distinguish between nil and an empty array because they represent different states.
  • Use reserveCapacity only when you have a real performance reason to preallocate space.

Course illustration
Course illustration

All Rights Reserved.