Swift Collection Types: Arrays, Dictionaries, and Sets Explained

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 4, 2024

Working with Collection Types in Swift

Collections in Swift allow you to store multiple values in a single variable. There are several types of collection in Swift such as arrays, dictionaries, and sets. In this tutorial, we will explore how to work with these collection types in Swift.

Arrays

An array is an ordered collection of values. You can create an array in Swift using the following syntax:

var fruits = ["apple", "banana", "orange"]}

To access elements in an array, you can use subscripts with the index of the element like this:

let firstFruit = fruits[0]}

Dictionaries

A dictionary is a collection of key-value pairs. You can create a dictionary in Swift like this:

var ages = ["Alice": 30, "Bob": 25, "Charlie": 35]}

To access values in a dictionary, you can use the key like this:

let aliceAge = ages["Alice"]}

Sets

A set is an unordered collection of unique values. You can create a set in Swift like this:

var uniqueNumbers: Set = [1, 2, 3, 4, 5]}

Unlike arrays, sets do not have a specific order, and each element in a set is unique.

Working with collection types in Swift allows you to efficiently store and manipulate data in your applications. By understanding the differences between arrays, dictionaries, and sets, you can choose the appropriate collection type for your specific use case.