Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Introduction to Collections in Swift

Introduction to Collections in Swift

What are Collections?

In Swift, collections are data structures that hold multiple values. The three primary types of collections in Swift are arrays, dictionaries, and sets. Each of these collections serves a unique purpose and provides various functionalities depending on the use case.

1. Arrays

An array is an ordered collection of values. You can access elements in an array using their index, which starts at 0. Arrays can hold any type of data, including strings, integers, and even other collections.

Example of Array:
let fruits = ["Apple", "Banana", "Cherry"]

To access the first element:

let firstFruit = fruits[0]
firstFruit: "Apple"

2. Dictionaries

A dictionary is an unordered collection of key-value pairs. Each key must be unique, and it is used to access the corresponding value. Dictionaries are useful when you want to store related pieces of information.

Example of Dictionary:
let person = ["name": "John", "age": 30]

To access the value associated with a key:

let name = person["name"]
name: "John"

3. Sets

A set is a collection of unique values. Sets are unordered, which means that the elements do not have a defined order. They are particularly useful when you want to ensure that no duplicates are stored.

Example of Set:
let colors: Set = ["Red", "Green", "Blue"]

Attempting to add a duplicate value:

var moreColors = colors
moreColors.insert("Red")
moreColors: {"Red", "Green", "Blue"}

Conclusion

Collections are essential in Swift for managing groups of related data. Understanding how to use arrays, dictionaries, and sets will significantly enhance your programming capabilities in Swift. Each collection type has its strengths and is suited to specific tasks, so it’s crucial to choose the right one for your needs.