SWIFT
Swift Array: Syntax, Usage, and Examples
A Swift array stores a collection of values in an ordered list. Arrays let you manage multiple items using a single variable, whether you’re working with numbers, strings, custom structs, or any other type. Arrays in Swift are flexible, type-safe, and come with powerful built-in methods for filtering, sorting, and modifying data.
How to Use an Array in Swift
You can create an array Swift-style using square brackets and either provide the type explicitly or let Swift infer it from the values.
Creating Arrays
// Explicit type
var numbers: [Int] = [1, 2, 3, 4, 5]
// Inferred type
let names = ["Alice", "Bob", "Charlie"]
Arrays can also be empty:
var emptyArray: [String] = []
You can even initialize arrays with a repeating value:
let zeros = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
Accessing Array Elements
Use index numbers to get or modify values.
var fruits = ["Apple", "Banana", "Cherry"]
print(fruits[0]) // "Apple"
fruits[1] = "Blueberry"
Swift arrays are zero-indexed, so indexing starts at 0.
When to Use Swift Arrays
You’ll use a Swift array in nearly every app you build. It’s the go-to data structure when you need to:
- Store a list of similar values, like product IDs or user messages.
- Sort, filter, or transform a group of elements.
- Pass or return multiple items from a function.
- Group data that needs to be displayed in a list or table view.
- Manage dynamic sets of values, like search results or selected options.
Whether you're dealing with five items or five million, arrays help you keep your data organized and accessible.
Examples of Array Swift Operations
Append Items to an Array
You can add one item or append multiple items to a Swift array.
var numbers = [1, 2, 3]
numbers.append(4) // [1, 2, 3, 4]
numbers += [5, 6] // [1, 2, 3, 4, 5, 6]
You can even append a struct to an array of custom types.
struct Task {
let title: String
}
var tasks = [Task]()
tasks.append(Task(title: "Do laundry"))
This approach is common when managing models or objects in SwiftUI or UIKit apps.
Filter an Array
Use the filter
method to keep only elements that match a condition.
let numbers = [1, 2, 3, 4, 5, 6]
let even = numbers.filter { $0 % 2 == 0 } // [2, 4, 6]
Filtering is useful in search, validation, and view rendering.
Check if an Array Contains an Item
The contains
method returns true if the value exists.
let fruits = ["Apple", "Banana", "Cherry"]
print(fruits.contains("Banana")) // true
Use this for validation, conditions, or user selections.
Sort an Array
Sorting is simple with sorted()
.
let scores = [75, 92, 85, 61]
let sortedScores = scores.sorted() // [61, 75, 85, 92]
Use sorted(by:)
for custom sorting:
let names = ["Zara", "Liam", "Olivia"]
let descending = names.sorted(by: >) // ["Zara", "Olivia", "Liam"]
Slice a Swift Array
You can get a subset of an array using slicing:
let letters = ["A", "B", "C", "D", "E"]
let subset = letters[1...3] // ["B", "C", "D"]
Slicing is useful for pagination, previews, and sampling.
Reverse a Swift Array
Reversing is easy with reversed()
:
let original = [1, 2, 3]
let reversed = Array(original.reversed()) // [3, 2, 1]
You need to convert it back to an array because reversed()
returns a sequence.
Learn More About Swift Arrays
Array of Int to Int
Sometimes you need to transform an array of integers into a single value. Use reduce()
for that.
let values = [1, 2, 3, 4]
let sum = values.reduce(0, +) // 10
This technique is common in analytics or score calculations.
Append Array to Another Array
To merge two arrays, use +=
or append(contentsOf:)
.
var first = [1, 2, 3]
let second = [4, 5]
first.append(contentsOf: second) // [1, 2, 3, 4, 5]
This is handy for combining results from multiple sources.
Remove Elements
Use remove(at:)
, removeLast()
, or removeAll()
depending on your needs:
var colors = ["Red", "Green", "Blue"]
colors.remove(at: 1) // ["Red", "Blue"]
colors.removeLast() // ["Red"]
colors.removeAll() // []
You can also remove elements conditionally using removeAll(where:)
.
Map and Transform
Swift arrays let you change each item using map()
:
let names = ["Amy", "Brian"]
let uppercased = names.map { $0.uppercased() } // ["AMY", "BRIAN"]
Use map()
to convert types, like turning strings into structs or numbers into strings.
Array Capacity and Performance
While Swift arrays grow dynamically, you can preallocate space for performance:
var list = [Int]()
list.reserveCapacity(1000)
This avoids multiple memory reallocations when appending large data sets.
Swift Array Properties and Methods
Here are more built-in tools to explore:
count
: Returns the number of elements.isEmpty
: Returnstrue
if the array has no items.first
/last
: Access the first or last item.index(of:)
: Finds the index of a specific value.shuffle()
: Randomizes the order of items.joined(separator:)
: Combines strings in an array into one.
Example:
let words = ["Hello", "World"]
let sentence = words.joined(separator: " ") // "Hello World"
Swift Array of Custom Types
You can build arrays with your own models and sort, filter, or search through them just like built-in types.
struct Product {
let name: String
let price: Double
}
let products = [
Product(name: "Keyboard", price: 49.99),
Product(name: "Mouse", price: 29.99),
Product(name: "Monitor", price: 199.99)
]
let expensive = products.filter { $0.price > 50 }
This makes Swift arrays powerful tools for modeling and managing app data.
Best Practices for Using Swift Arrays
- Use type inference when possible for cleaner code.
- Avoid force-unwrapping with
first
,last
, or index access. - Prefer
isEmpty
overcount == 0
for readability. - Use
guard
orif let
to safely work with optional values likefirst
. - Consider
Set
for faster lookup if order isn’t important. - Don’t mutate arrays in views or shared state without caution—consider using
@State
or@Published
.
A Swift array is more than a list—it’s the backbone of dynamic, flexible, and clean app logic. Whether you're displaying a to-do list, filtering search results, or sorting data, arrays in Swift give you the tools to build powerful and efficient features.
With support for slicing, reversing, mapping, and combining arrays, you can write expressive, readable code that’s easy to maintain and expand.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.