How to Create an Array in Swift

Use arrays in Swift when you need to store multiple values of the same type in one ordered collection. Arrays are perfect for lists, feeds, tasks, scores, and SwiftUI-driven data.

What you’ll build or solve

You’ll learn how to create arrays in Swift with literal syntax, explicit typing, empty arrays, and common model collections. You’ll also know when Set is a better fit.

When this approach works best

This approach is the right choice when order matters and duplicate values are allowed.

Common real-world scenarios include:

  • Todo lists
  • Lesson feeds
  • Product catalogs
  • Scores
  • Chat messages

This is a bad idea when uniqueness matters more than order.

Prerequisites

You only need:

  • Basic Swift variables
  • Familiarity with collections
  • Understanding of type inference

Step-by-step instructions

Step 1: Create an array with literal syntax

The most common pattern uses square brackets.

let lessons = ["HTML", "CSS", "Swift"]

Swift infers this as [String].

This is the cleanest default syntax.

Step 2: Add an explicit array type

For empty or public collections, declare the type.

let scores: [Int] = [95, 88, 76]

This improves clarity when needed.

Step 3: Create an empty array

Empty arrays need a type hint.

var tasks: [String] = []

This is common for dynamic data sources.

Step 4: Store custom models

Arrays scale naturally to structs.

struct Lesson {
    let title: String
}

let lessons = [
    Lesson(title: "Swift Basics"),
    Lesson(title: "Closures")
]

This is the most common real-world app pattern.

What to look for:

  • Arrays preserve order
  • Duplicates are allowed
  • Empty arrays need explicit types
  • Great for SwiftUI lists
  • Use Set for uniqueness

Examples you can copy

String list

let tags = ["ios", "swift"]

Empty scores

var scores: [Int] = []

Model collection

let users: [User] = []

Common mistakes and how to fix them

Mistake 1: Using empty arrays without types

What the reader might do:

let items = []

Why it breaks: Swift cannot infer the element type.

Corrected approach:

Add [Type].

Mistake 2: Using arrays when uniqueness matters

What the reader might do:

Track unique tags in an array.

Why it breaks: duplicates can appear.

Corrected approach:

Use Set.

Mistake 3: Using immutable arrays for changing data

What the reader might do:

let tasks = ["One"]
tasks.append("Two")

Why it breaks: let arrays cannot change.

Corrected approach:

Use var.

Troubleshooting

If Swift cannot infer the type, add [Type].

If appending fails, switch from let to var.

If duplicates are a problem, consider Set.

If arrays power SwiftUI, make sure the data is observable.

Quick recap

  • Use arrays for ordered collections
  • Duplicates are allowed
  • Empty arrays need explicit types
  • Use var for mutable arrays
  • Prefer Set for uniqueness