Collections and Control Flow (Arrays, Dictionaries) (if, Switch ) Flashcards
What are the 3 collection types in swift?
Array, dictionary and sets
When you concatenate two things, what must the have in common?
They must be of the same type. So String and string or [Int] and [Int]
Given an array:
let a = [2.0, 1.1, 2.3, 5.4]
What is a’s type?
[Double]
let a = [1,2,3]
a.insert(4, at: 3)
The code raises an error. Why?
The array is immutable and cannot be changed
let a = [1, 2, 3]
a[3]
The code above crashes. Why?
The index value provided is out of bounds
To get the 4th item out of an array, which index number do we use?
3
TF: An array preserves the order of its elements, i.e., it is an ordered collection.
True
Remove the 5th item in this array. var a = [10, 1, 12, 22, 96, 14]
a.remove(at: 4)
What exactly is a dictionary?
Set of key, value pairs
What happens when you try to get a value that does not exist in an array vs dictionary?
Array → it crashes
Dictionary → it will return nil because dictionaries are always of an optional type.
Given the following dictionary: let dict = [1: "someValue", 2: "anotherValue"]
What is the dictionary’s type?
[Int : String]
When we try to access a value using a key that doesn’t exist in a dictionary, what result do we get?
A nil value
TF: The following code snippets are equivalent
dict.updateValue(“yetAnotherValue”, forKey: 3)
And
dict[3] = “yetAnotherValue”
True
TF: A dictionary is an ordered collection and preserves the order of key-value pairs added to it
False
What is an if statement?
if statement is a conditional statement that executes some code depending on the conditions stated.