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.
If you have a bunch of possibilities in an if else statement, when will the condition be met?
As soon as a condition is satisfied from top to bottom, the code will be executed.
Give all the possibilities when using && or ||.
True && True → True True && False → False False && False → False True || True → True True || False → True False || False → False
How does a switch statement work?
Switch (value to consider) { case value1: response to value1 case value1: response to value2 default : do this }
What's missing from this switch statement? let months = 1...12
for month in months { switch month { case 1: print("January") } }
The above code will not compile because switch statements need to be exhaustive with case statements for all expected values or a default statement.
var isAvailable = true var isCheap = true
var status: String
if !isCheap && !isAvailable { status = "super rare" } else if isCheap && isAvailable { status = "not rare" } else if !isCheap && isAvailable { status = "somewhat rare" } else { status = "common" }
What does status evaluate to?
“Not rare”
TF: Both the AND and OR operators use short circuit evaluation
True
What does the following statement evaluate to?
!true || !false) && (true && !false
True