- Learning Objectives
- Collection Types
- Activity on Arrays & Dictionaries
- Break
- Control Flow
- Activity on Control Flow
- Wrap Up
By the end of this lesson, students should be able to:
- Create Arrays to store collections of data
- Create Dictionaries to store collections of data
- Differentiate & use the various types of loops in Swift
- Apply Optionals in creating and using different collection types
The most common collection type in Swift.
Collections are containers that let us store multiple values together.
Arrays store multiple values of the same type in a list.
An ordered collection of values of the same type
Arrays are zero-indexed.
Zero-indexed means the index of the first element is always 0, the second is 1, third is 2 and so on.
The last element has an index equal to the number of values in the array minus one.
In the example above, there are 4 elements of type String. Their indices go from 0 to 3.
Using an array literal
let concentrations = ["MOB", "BEW", "FEW", "DS"]
The type is [String]
An array literal is a list of values separated by commas, inside square brackets.
The type inside the square brackets tell us the type of values the array can store.
var concentrations = []
Empty collection literal requires an explicit type
If we need an empty array, we need to specify it's type since Xcode can't infer it.
Here's two ways to do it.
var concentrations : [String] = []
var concentrations = [String]()
We can add elements to an array using different methods:
concentrations.append("ROB")
concentrations += ["ROB"]
concentrations.insert("ROB", at: 2)
The append method will add the new element at the end of the array.
+= operator will also add it at the end.
The insert method lets us define the position in the array where we want the new element.
There are several alternatives to remove elements.
concentrations.removeLast()
concentrations.remove(at:4)
Both methods will do two things, they will remove the element while also returning it in case you need to store it and use it.
There are several alternatives to remove elements.
concentrations[0] = "MOBILE"
Here we use the subscript syntax to update the content.
Important: Be sure to NOT use an index that goes beyond the bounds of the array. Or else the program will crash.
concentrations.swap(1,2)
The swap method lets us exchange the position of two elements.
concentrations.sort()
concentrations.sorted()
The sort method will order the elements in the array.
The sorted method will return a sorted copy of the array.
Complete these practice problems in a playground.
An unordered collection of pairs.
Each pair has a key and a value.
Keys are unique, they can't appear more than once in a dictionary.
All keys have to be of the same type and all values have to be of the same type.
Dictionaries are useful when when want to look up values given an identifier. Just like looking up words in a dictionary.
Using a dictionary literal.
var coursesAndStudents = ["MOB":30, "BEW":40, "FEW":30, "DS":40]
The type is [String:Int]
A list of key-value pairs separated by commas inside square brackets.
var coursesAndStudents : [String:Int] = [:]
We can use subscripting just like in arrays. But since elements are not ordered, instead of looking for an index, we look for a key.
print(coursesAndStudents["FEW"]!)
Why are we using force unwrapping?
The return type is an optional. Meaning the dictionary will first check if there is a value with the key provided. If there is it will return the value, nil otherwise.
coursesAndStudents.updateValue(15, forKey: "ROB")
coursesAndStudents["ROB"] = 15
These both serve as a way to add a new pair and also to update an existing pair. The code will update the value for the key given or create a new pair if it can't find it.
coursesAndStudents.removeValue(forKey:"ROB")
coursesAndStudents["ROB"] = nil
These will remove the key and the corresponding value from the dictionary.
There is a difference between the two methods. Assigning a key to nil will remove the value and the key entirely. If we wanted to keep the key and set the value to nil (in case we are dealing with optionals) we should use the removeValue method.
An unordered collection of unique values of the same type.
let plantCollection: Set<String> = ["Pothos", "Monstera", "Calathea"]
let plantCollection = Set(["Pothos", "Monstera", "Calathea"])
The first option uses a type annotation while the second one let's the compiler infer the type.
let plantCollection: Set<String> = ["Pothos", "Monstera", "Calathea", "Pothos"]
print(plantCollection)
What will be the result in the console?
The result will be an unordered list and it will also show unique values. So even if we added the same plant twice, the set will make sure all the elements are unique.
print(plantCollection.contains("Monstera"))
plantCollection.insert("Ficus")
let removedPlant = plantCollection.remove("Calathea")
Complete these practice problems in a playground.
Individually answer:
- When would you use a Dictionary vs an Array? Are there advantages/disadvantages when using each?
- When would you use a Set vs an Array? Are there advantages/disadvantages when using each?
- Is type annotation better than type inference?
Discuss your answers with a neighbor.
- Do you share the same answers?
- Any disagreements?
- A question you both have for the instructor? Raise your hand to get help.
while <CONDITION> {
// code that will loop
}
The loop checks the condition for every iteration. When the condition is false, it will stop.
repeat {
// code that will loop
} while <CONDITION>
The condition is evaluated at the end of the loop.
var result = 0
while result < 5{
result = result + (result + 1)
}
var result = 0
repeat{
result = result + (result + 1)
} while result < 10
var result = 0
while true{
result = result + (result + 1)
if result >= 10{
break
}
}
We can end the loop using the break
statement. It will stop the execution of the loop and continue with the code after the loop.
let closedRange = 0...8
Goes from 0 to 8 inclusive.
let halfOpenRange = 0..<8
Goes from 0 up to, but not including 8.
for <CONSTANT> in <RANGE> {
// code that will loop
}
let count = 5
var result = 0
for i in 1...count{
result += i
}
When working with loops that update the value of a variable it is useful to do a whiteboard test and check what is its value in each iteration.
Its important to notice that the constant i is only visible inside the scope of the for loop.
Sometimes we don't need the loop constant, we just want to run a block of code certain number of times.
for _ in 0..count{
// code that will loop
}
var result = 0
for i in 1...10 where i % 2 == 1 {
result += i
}
This for loop has a where clause. It will loop through all of the values in the range but will only execute the block then the where condition is true.
Looping items in an array
var coursesAndStudents = ["MOB", "BEW", "FEW", "DS"]
for course in coursesAndStudents {
print(course)
}
Looping items in a dictionary
var coursesAndStudents = ["MOB":30, "BEW":40, "FEW":30, "DS":40]
for (course, countStudents) in coursesAndStudents {
print("\(course): \(countStudents)")
}
Complete these practice problems in a playground.
- Challenge: Conway's Game of life found here: Array's & Loops Swift Playgrounds
- Apple's documentation on Arrays & Dictionaries
- For more practice, try this out: Optionals & Dictionaries Swift Playgrounds