Skip to main content
April 1, 2026Noble Desktop Publishing Team/8 min read

Collection Types: Arrays & Dictionaries

Master Swift Collections for iOS App Development

Swift Collection Types Overview

Arrays

Ordered collections of data accessed by zero-indexed positions. Perfect for storing sequential information like playlists or game levels.

Dictionaries

Unordered collections using key-value pairs for data access. Ideal for storing related attributes like user profiles or settings.

Topics Covered in This iOS Development Tutorial:

Declaring Arrays & Accessing Their Indexes, Working with Mutable Arrays, Creating an Array Without an Initial Value, Declaring, Accessing, & Modifying Dictionaries, Creating a Dictionary Without an Initial Value

Exercise Overview

While constants and variables excel at storing individual values, real-world iOS applications require more sophisticated data structures. Whether you're building a task management app, a contact directory, or a social media platform, you'll need to handle collections of related data efficiently. This exercise introduces two fundamental collection types that form the backbone of iOS development: arrays and dictionaries. Mastering these data structures is essential for any serious iOS developer, as they're used extensively throughout UIKit, SwiftUI, and most third-party frameworks you'll encounter in professional development.

Getting Started

Let's set up a Swift Playground to explore these collection types hands-on. Playgrounds remain one of the most effective ways to experiment with Swift concepts and see immediate results.

  1. Launch Xcode if it isn't already open.

  2. Go to File > New > Playground.

  3. Under iOS, double–click on Blank.

  4. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  5. Save the file as: Collection Types.playground

  6. Click Create.

Xcode Playground Setup

1

Create New Playground

Launch Xcode and navigate to File > New > Playground, selecting Blank template under iOS

2

Save to Project Directory

Navigate to Desktop > Class Files > yourname-iOS App Dev 1 Class and save as Collection Types.playground

3

Initialize Workspace

Click Create to begin working with Swift collections in the interactive playground environment

Declaring Arrays & Accessing Their Indexes

Arrays are the workhorses of iOS development, storing ordered sequences of data that power everything from table views to complex data models. An array maintains an ordered list of elements, where each item occupies a specific position called an index. Understanding that arrays use zero-based indexing is crucial—the first element sits at index 0, the second at index 1, and so forth.

This indexing system isn't arbitrary; it reflects how memory allocation works at the hardware level and enables efficient data access patterns that modern apps depend on. When you scroll through your Instagram feed or navigate a music playlist, arrays are managing that data behind the scenes, with UI components accessing specific indexes to display content.

  1. Arrays use familiar variable declaration syntax, but enclose their comma-separated values in square brackets []. Replace the default var str line with this game level array:

    // ARRAYS
    let levels = [1,2, 3,4, 5]
  2. To retrieve a specific array element, combine the array name with brackets containing the target index. Access the first element (index 0) with this syntax:

    let levels = [1,2, 3,4, 5]
    levels[0]
  3. The Playground results sidebar displays: 1. This confirms that index 0 contains the first array element—in this case, the integer 1.

  4. Now access the final element at index 4:

    let levels = [1,2, 3,4, 5]
    levels[0]
    levels[4]
  5. The sidebar shows: 5, confirming successful access to the last element.

  6. String interpolation allows you to embed array values directly into text output. Add this print statement:

    levels[4]
    print("This game is made up of \(levels[4]) levels")
  7. The output reads: This game is made up of 5 levels

  8. Production code rarely knows array sizes in advance—data comes from APIs, user input, or dynamic sources. Swift's count property provides runtime array size information. Update the print statement:

    print("This game is made up of \(levels.count) levels")

    This produces identical output but adapts automatically to arrays of any size—a crucial pattern for robust app development.

Zero-Indexed Arrays

Arrays in Swift are zero-indexed, meaning the first item has an index of 0, the second item is 1, and so forth. This is fundamental to understanding array access patterns.

Array Index Visualization

Index 0
1
Index 1
2
Index 2
3
Index 3
4
Index 4
5

Working with Mutable Arrays

Real applications require data that changes over time. User-generated content, dynamic API responses, and interactive features all demand mutable collections. The distinction between constants (let) and variables (var) becomes critical when working with arrays that need modification capabilities.

  1. Player rosters change frequently in games, making them perfect candidates for mutable arrays. Create a variable array to handle dynamic player data:

    print("This game is made up of \(levels.count) levels")
    
    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
  2. The results sidebar displays all player names, confirming successful array creation.

  3. Adding elements to arrays is a common operation in iOS apps—think of adding items to shopping carts or messages to chat threads. Use the append method to add a new player:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")

    NOTE: Methods are functions associated with specific types. Arrays come with numerous built-in methods that simplify common operations—you'll use these extensively as you build more complex applications.

  4. The sidebar now shows Max appended to the array's end. The append method always adds new elements at the final position, maintaining the existing order.

  5. Removing elements is equally important for maintaining clean data. When Steve leaves the game, remove him using the targeted removal method:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)

    The remove(at:) method takes an index parameter specifying which element to delete. Remember: John occupies index 0, making Steve index 1.

  6. Examine the updated array contents by referencing the array name:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)
    currentPlayers
  7. Steve has vanished from the results, and importantly, the remaining elements have shifted to fill the gap. Laurie now occupies index 1—arrays maintain contiguous indexing automatically.

  8. Sometimes you need precise control over element placement. The insert method places new elements at specific positions. Add Omar between Laurie and Holly:

    var currentPlayers = ["John", "Steve", "Laurie", "Holly", "Sam"]
    currentPlayers.append("Max")
    currentPlayers.remove(at: 1)
    currentPlayers
    currentPlayers.insert("Omar", at: 2)
  9. The sidebar displays: ["John", "Laurie", "Omar", "Holly", "Sam", "Max"], confirming Omar's insertion at index 2.

    NOTE: Swift's type system enforces homogeneous arrays—all elements must share the same data type. This type safety prevents runtime errors and enables powerful compiler optimizations that make your apps faster and more reliable.

Constants vs Variables for Arrays

Featurelet (Constants)var (Variables)
MutabilityImmutableMutable
Use CaseFixed dataChanging data
Methods AvailableRead-onlyAppend, Remove, Insert
Recommended: Use variables when you need to modify array contents during runtime

Array Modification Methods

append()

Adds new elements to the end of an array. Always places items at the final position.

remove(at:)

Removes elements at a specific index position. Automatically shifts remaining elements to fill gaps.

insert(_:at:)

Inserts elements at any specified position within the array, shifting existing elements as needed.

Creating an Array Without an Initial Value

Many real-world scenarios require empty arrays that populate dynamically. High score systems, user favorites, or shopping carts all start empty and grow based on user interaction. Swift provides clean syntax for initializing typed empty arrays.

  1. Create an empty integer array for high scores using explicit type annotation:

    currentPlayers.insert("Omar", at: 2)
    
    var highScores = [Int]()

    Without initial values, Swift can't infer the array type, requiring explicit [Int] annotation. The empty parentheses () initialize an empty array instance ready for population.

  2. Add the first high score using the familiar append method:

    var highScores = [Int]()
    highScores.append(148)

    The highScores array now contains one element, demonstrating how empty arrays seamlessly accept new data.

Empty Array Initialization

When creating arrays without initial values, you must specify the data type explicitly since Swift cannot infer the type from empty collections.

Declaring, Accessing, & Modifying Dictionaries

While arrays excel at ordered data, many applications need associative relationships—connecting related pieces of information without relying on positional indexing. Dictionaries store unordered key-value pairs, where unique keys provide direct access to associated values. This structure mirrors real-world relationships: employee IDs linking to personnel records, product codes connecting to inventory data, or user preferences tied to account settings.

Modern iOS apps leverage dictionaries extensively for JSON parsing, caching strategies, and configuration management. Understanding dictionary operations is essential for working with web APIs and complex data relationships.

  1. Create a player attributes dictionary using key-value syntax:

    highScores.append(148)
    
    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]

    Dictionaries also use square brackets but contain key-value pairs separated by colons, with commas delimiting each pair. This syntax closely resembles JSON, making it intuitive for developers working with web services.

  2. Access dictionary values using subscript syntax with string keys:

    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]
    playerAttributes["name"]

    The sidebar displays John, demonstrating direct key-based access.

  3. Try accessing a different key to reinforce the pattern:

    // DICTIONARIES
    var playerAttributes = ["name": "John", "city": "Brooklyn", "state": "New York", "username": "johnnyboy"]
    playerAttributes["name"]
    playerAttributes["city"]

    Brooklyn appears on the right, confirming successful key lookup.

  4. Updating dictionary values requires the updateValue method for safe modification. Update John's name to include his surname:

    playerAttributes["name"]
    playerAttributes["city"]
    
    playerAttributes.updateValue("John Jones", forKey: "name")
  5. The sidebar shows John—the previous value that was replaced. Verify the update by accessing the key again:

    playerAttributes.updateValue("John Jones", forKey: "name")
    playerAttributes["name"]

    Now John Jones appears, confirming the successful update. Swift Playgrounds display replaced values to show what changed during the operation.

  6. Remove sensitive data using the removeValue method. Delete the name for privacy:

    playerAttributes.updateValue("John Jones", forKey: "name")
    playerAttributes["name"]
    
    playerAttributes.removeValue(forKey: "name")
  7. Verify the removal by examining the entire dictionary:

    playerAttributes.removeValue(forKey: "name")
    playerAttributes

    The output shows city, state, and username without the name key, confirming successful removal. Expand the results sidebar using the resize handle splitter if the output is truncated.

  8. Adding new key-value pairs uses simple assignment syntax. Add contact information:

    playerAttributes.removeValue(forKey: "name")
    playerAttributes
    playerAttributes["phone"] = "212-765-4321"
  9. Review the complete dictionary structure by typing playerAttributes at the file's bottom.

Arrays vs Dictionaries

FeatureArraysDictionaries
Data OrganizationOrdered by indexUnordered key-value pairs
Access MethodNumeric indexString or other key
Use CaseSequential dataRelated attributes
PerformanceIndex-based lookupKey-based lookup
Recommended: Choose dictionaries when you need to associate related data with meaningful identifiers

Dictionary Operations

updateValue()

Modifies existing values for specified keys. Returns the old value to confirm the update operation.

removeValue()

Deletes key-value pairs from the dictionary. Completely removes both the key and its associated value.

Direct Assignment

Add new key-value pairs using bracket notation. Creates new entries or updates existing ones seamlessly.

Creating a Dictionary Without an Initial Value

Like arrays, dictionaries can start empty and populate dynamically. This pattern is particularly useful for user preferences, cache systems, or any data structure that builds over time based on user interaction or external data sources.

  1. Initialize an empty dictionary with explicit type annotations for both keys and values:

    playerAttributes["phone"] = "212-765-4321"
    playerAttributes
    
    var playerPref = [String: String]()

    The syntax follows the pattern: var nameOfDictionary = [keyType: valueType](). Both keys and values must have consistent types throughout the dictionary.

  2. Add the first preference using subscript assignment:

    var playerPref = [String: String]()
    playerPref["speed"] = "fast"

    This creates a key-value pair where speed maps to fast.

  3. Examine the dictionary contents by typing playerPref at the bottom.

    NOTE: Consider experimenting with additional preferences like difficulty levels (easy, medium, hard) or display settings. The count property works with dictionaries just as it does with arrays, providing useful metadata about your collections.

  4. Save and close the file. Keep Xcode open, as we'll use it in the next exercise.

You've now mastered the fundamental collection types that power iOS applications. Arrays and dictionaries form the foundation for more advanced data structures and design patterns you'll encounter in professional iOS development, from Core Data relationships to SwiftUI state management.

Dictionary Type Declaration

Empty dictionaries require explicit type declaration using [KeyType: ValueType]() syntax, defining both key and value data types upfront.

Collection Best Practices

0/4

Key Takeaways

1Arrays store ordered collections of data accessed through zero-indexed positions, making them ideal for sequential information like game levels or playlists
2Mutable arrays declared with 'var' support modification methods like append(), remove(at:), and insert(_:at:) for dynamic data management
3Dictionaries organize data as unordered key-value pairs, perfect for storing related attributes like user profiles or configuration settings
4Empty collections require explicit type declarations since Swift cannot infer types from collections without initial values
5The count property provides dynamic sizing information for both arrays and dictionaries, eliminating the need for hardcoded lengths
6Dictionary operations include updateValue() for modifications, removeValue() for deletions, and direct bracket assignment for additions
7All elements in Swift collections must be of the same type due to type inference and safety requirements
8Swift Playgrounds provide immediate feedback on collection operations, showing both old and new values during modification processes

RELATED ARTICLES