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.
Learn Swift on Mimo
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.
Swift
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.
Swift
let scores: [Int] = [95, 88, 76]
This improves clarity when needed.
Step 3: Create an empty array
Empty arrays need a type hint.
Swift
var tasks: [String] = []
This is common for dynamic data sources.
Step 4: Store custom models
Arrays scale naturally to structs.
Swift
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
Setfor uniqueness
Examples you can copy
String list
Swift
let tags = ["ios", "swift"]
Empty scores
Swift
var scores: [Int] = []
Model collection
Swift
let users: [User] = []
Common mistakes and how to fix them
Mistake 1: Using empty arrays without types
What the reader might do:
Swift
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:
Swift
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
varfor mutable arrays - Prefer
Setfor uniqueness
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot