Collections
Collections
Collections is a free Swift Academy lesson on CoddyKit — lesson 1 of 1. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 1 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction
Hello,
In this lesson, we will learn about collection types in Swift, which is one of the most important topics.
So let's start.
There are 3 collection types in Swift.
Array → Sequential collection types.
Set → Unordered and unique collection types.
Dictionary → Collection Types without order and in key-value pairs.
mutable - immutable
Whether our collection types are immutable or mutable is determined by our definition.
If we define it with a let statement, it will be immutable, while it is mutable if we define it with var.
If the value we defined will not change afterwards, using let will provide a performance advantage for the compiler to run more optimized.
Array
Array
Array is the collection type used to keep data sequentially. With the Swift 3 version, all elements in an array do not have to be of the same type.
The syntax of a simple Array definition is shown in our example below.
// Let's create an empty array.
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."Create array with default value
Create array with default value
In some cases, we may want to create an array with a default value and a specific size. For this, we need to pass two arguments to the Array constructor.
These arguments specify what the default value is and how many elements the array will have.
var threeDoubles = Array(repeating: 0.0, count: 3)
print(threeDoubles)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
print(anotherThreeDoubles)
var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles)
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]Creating an Array using Array Literal
Creating an Array using Array Literal
In our previous example, we learned how to create an empty Array. However, in some cases, we may want to create an Array with an Array Literal.
Let's learn its usage on the example.
/*
We have defined a variable named catList,
and with the [String] statement we specified
that its type is an Array containing String elements.
*/
var catList: [String] = ["Garfield", "Tom"]
print(catList)
/*
It will understand that the array is an Array containing
String statements, since we assign a value that
defines the variable. (Swift type inference)
*/
var shoppingList = ["Eggs", "Milk"]
print(shoppingList)Accessing array value
Accessing the value of the array
When we want to reach a certain index element in a sequence, it is sufficient to call it with the following syntax.
myArray [index]
Let's look at the example.
// We have defined an array with 3 elements of type Int.
var numbers:[Int] = [1, 5, 21]
// Arrays start from Index 0. For example, in order to reach the value 5, which is the 2nd element, we need to access the 1st index.
var a = numbers[1]
print( "Value of numbers at index 1 is \(a)" )Adding new elements to the Array
Adding new elements to the Array
we can add a new item to Array.
In the example below, an Array named catList is defined. And in the next step, a new item has been added to this Array with the append method.
// The Array named catList was defined with 1 initial element.
var catList = ["Tom"]
/*
We are adding a new item with a Garfield
value using the append method.
*/
catList.append("Garfield")
// Our array will now have 2 elements.
/*
With the + = operator, we can do the
work that the append method does.
*/
catList += ["Sylvester"]
Adding data to a specific index in the array
Adding data to a specific index in the array
The value I added with the append method in our previous example will be added to the end of the array. However, sometimes we may want to add it to a specific index. We will use the insert method for this.
The syntax will look like this.
myArr.insert ("The data to add", at: index);
Let's find out with an example.
var catList = ["Tom"]
catList.insert("Garfield", at: 1)
print(catList)
Deleting a specific element in the array
Deleting a specific element in the array
The remove method is used to delete an element in a certain index in an array.
var shoppingList = ["Apple", "Cherry", "Cheese"]
let shoppingListOne = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string
let shoppingListTwo = shoppingList.removeLast()
// the last item in the array has just been removed
print(shoppingListTwo)Array iteration
We can iterate an array we have with the for-in.
Let's take a look at the example.
var shoppingList = ["Banana", "Orange", "Milk"]
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
Sets
Sets
Used to keep collections of the same type together without order.
As we can understand from the name, they are sets. And there cannot be two elements of the same value in the set.
creating empty set
We use the following example to create an empty set.
var catSet = Set<Character>()Creating Sets Using Array Literal
Creating Sets Using Array Literal
Array literal can be used to create a set. Note that although the value assigned here looks like an array, the type of variable is Set <String>.
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]Warning
With the use of Array literal, creating a set is not possible without defining a type. It can interfere with the Array. Therefore, we need to define the type.
At least we should use it as follows.
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]Set Methods
Set Methods
Let's take a look at the example
var favoriteGenres = ["Funk"]
print("I have \(favoriteGenres.count) favorite music genres.")
if favoriteGenres.isEmpty {
print("favoriteGenres is empty")
} else {
print("I have particular music preferences.")
}
if favoriteGenres.contains("Funk") {
print("Funk")
} Iterate the Set
Iterate the Set
Set type of swift does not have ordering. However, the sorted method can be used when iterating over the set value. This method freezes the elements of the set as array arrays.
let favoriteGenres = ["Classical","Jazz", "Hip hop"]
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hopDictionary
Dictionary
They are collection types that keep dictionary values as key-values and do not contain any sort.
Each value is kept with a unique key. This represents the ID of that value in the dictionary. It does not contain a sequence like Arrays. We can think like a dictionary in the real world.
So the identity of each value is more important than ranking.
Dictionary type can be defined by the shorthand type [Key: Value]. The use of shortcuts is more preferred.
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]dictionary access methods
We can find out how many elements a dictionary contains by the count method.
Besides, we can check if the dictionary is empty with the isEmpty method.
Let's do some examples of these methods.
var airports = ["LHR": "London", "IST": "Istanbul"]
print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."
airports["LHR"] = "London"
// the airports dictionary now contains 3 itemssubscript
The process of getting a subscript using is as follows. The result return to be optional.
var airports = ["DUB":"Dublin"]
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."
//Deletion
airports["APL"] = nil
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport."
updating dictionary
In addition to using the subscript above, there is a method for updating the dictionary.
The feature of this method is that after the update process takes place, it returns the old value before it was updated.
var airports = ["DUB": "Dublin"]
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."
Converting from Dictionary to Array is an example below.
Converting from Dictionary to Array is an example below.
let airports = ["IST":"Istanbul Airport", "DUB":"Dublin Airport"]
let airportCodes = [String](airports.keys)
print(airportCodes)
let airportNames = [String](airports.values)
print(airportNames)Congratulations
Congratulations 🎉
In this lesson, we learned how to use Collections in Swift.
See you in the next lesson.

Frequently asked questions
Is the “Collections” lesson free?
Yes — the full text of “Collections” is free to read here on the web, and the Swift Academy course includes 1 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Collections”?
Collections You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 1, so you can start here or from the beginning and move at your own pace.
How long does the “Collections” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.