Fundamentals Flashcards
Keyword to create an enumeration Type?
enum
What type of syntax do you use to access enums?
dot syntax
Can you use an enum in a switch statement?
Yes
How do you declare an enum with raw values?
enum ENUM_NAME: String {
case ENUM_CASE1 = “VALUE1”
case ENUM_CASE2 = “VALUE2”
}
How do you declare an enum with associated values?
enum ENUM_NAME { case ENUM_CASE1(CASETYPE1) case ENUM_CASE2(CASETYPE2) }
How do you access the value associated with an enum case in a switch statement?
case .ENUM_CASE(let VALUENAME):
What do you call variables within a Struct, Class?
Properties of a Struct, Class
Keyword to create different enumeration choices?
case
Do you have to write initializers for Structs?
No. Swift will automatically create a “memberwise initializer”
Do all properties of a struct need to be declared when instantiating an instance of a structure?
Yes
What do you call the object created from a Struct/Class?
Instance of a Struct/Class
Are dictionaries ordered or unordered?
Unordered
How do you access the enum’s raw value?
.rawValue getter
When you declare a variable as an enum type and you are setting it, can you use a shorter syntax?
Yes, use dot syntax. (exp: .caseItem)
How do you declare and initialize a dictionary using a literal format?
var DICT = [
“KEY1”: “VALUE1”,
“KEY2”: “VALUE2”
]
What do you call functions within a Struct, Class?
Methods of a Struct, Class
Are “switch case” statements labels capitalized?
No
How do you force unwrap optionals?
Using the bang (!) symbol after a variable name
When you set the value of a dictionary key to nil, does it remove it from the collection?
Yes
How do you declare and initialize an empty dictionary of type String: Int
var DICT: [String: Int] = [:]
What method can you call that returns a tuple containing an index and the value?
array.enumerated()
When Iterating a dictionary, could you get a different order of items?
Yes
When getting the value of a dictionary does it return an optional value?
Yes
What keyword do you use to define a tuple?
Parenthesis (ITEM1, ITEM2)
When a function returns a tuple can you define the labels associated with it?
Yes func MYFUNC() -> (LABEL1: String, LABEL2: Int) { }
When creating an enum is it a Type?
Yes
Can you nest Enums within a Struct?
Yes. When accessing from outside of Struct, full path is required Exp. Struct.Enum.case
Can you use a function as a closure?
Yes, but it’s a code smell if you are not using it somewhere else.
Can you use index notation to access a specific tuple?
Yes
When you don’t label your closure function variables, are they still accessible?
Yes. $0, $1, $2 …
How do you decompose a tuple? into variables
let (FIRST, SECOND) = (1, 2)
I want to sort an array in place what method can I use?
array.sort(by:) { }
What’s the syntax to label closure parameters?
after curly braces wrap parameter names in parenthesis followed by the “in” keyword.
list.map { (item) in
}
What String method can you use to return a Bool if string ends with certain characters?
”“.hasSuffix(“ending”)
When is it appropriate to omit the return value when writing a closure
If the calling method’s closure parameter is the final or only parameter
How do you map over an array
array.map(transform:) { (item) in … }
Can you break up tuples using nested arrays into variables?
Yes.. Exp:
let (key, (value1, value2) = $0
What affect does adding underscores when storing a whole number have?
None. Swift ignores them
What method can you use to iterate over all items in a collection?
list.forEach(body:) { (item) in … }
How do you know that a method takes a closure?
Look in the “Developer Documentation.” The function definition will show a Function Type as a Type for the specified parameter.
Exp:
sort(by: (Element, Element) -> Bool)
(Element, Element) -> Bool ; Is the function type for the closure.
I want to sort an array without modifying the calling array, How do I do that?
let newArray = array.sorted(by:) { }
How you create a multi-line strings?
Use triple quotes to start and end multi-line strings
var text = “””
Text
“””
Can you add Emoji’s in a string?
Yes
How do you count the characters in a string?
use .count getter
What String method can you use to uppercase the characters?
.uppercased()
What String method can you use to get a Bool if string starts with certain characters?
”“.hasPrefix(“beginning”)
When storing long numbers, is it possible to break them down using comma’s?
No, but you can break them up using underscores instead.
Does Swift support shorthand operators?
Yes.
count += 1 ; count -= 1
What Int method can you use to get a Bool if integer is multiple of something?
120.isMultiple(of: 3)
What Bool method can you use to flip a boolean to the opposite value?
.toggle()
exp: var isOpen = true
isOpen.toggle()
What is a “Half-open Range Operator?”
1..<10 - Range between 1 and 10 excluding the last number, so 1-9.
What does “Operator Overloading” mean?
Allows the same operators (+-*/, and so on) to do different things depending on the data type you use them with
What is a “Compound Assignment Operator?”
Syntactical sugar for var = var + 1
var += 1
What affect does using “Comparison operators” on two strings?
Compares if they are in alphabetical order
Do you need to explicitly add a break statement to each switch case?
No. Swift only matches one case, if you need you need to more on to the next use the keyword: “fallthrough”
Example of a condition statement?
if a > 1 { } else if a < 1 {} else {}
What does “Conditional Short-Circuiting” mean?
Conditional expressions are evaluated from left-right, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression.
Does Swift yell at you if you don’t use the value returned from a for .. in loop? If so, how do you avoid this?
Yes. Use an underscore as the value name to ignore it.
When building a conditional with multiple expressions, should you use parenthesis?
Yes. Specially if expression includes an OR expression
What is the “Ternary Operator?”
let answer: String = true ? “True” : “False”
When creating a switch statement, do you need to have a default case?
Yes. all cases must be exhaustive!
What is a “Closed Range Operator?”
1…10 - Range between 1 and 10 including the last number, so 1-10
How do you write a while loop?
while count <= 20 {
count += 1
}
When you “break” out of a loop that is a nested loop, will it break out of all the loops?
No. You will need to add a label to the outer loop to break out of nested loops
outerLoop: for..in { for..in { break outerLoop } }
How do you know to use for .. in or while loops?
For … in loop = Finite sequences
While loop = Unknown amount of sequences
When should you use the repeat {} while loop?
When you want your condition to execute at least once before checking the condition.
Example of repeat {} while
let numbers = [1, 2, 3, 4, 5] var random: [Int]
repeat {
random = numbers.shuffled()
} while random == numbers
What Array method can you use to create, and shuffle a new copy of an array?
[].shuffled()
What character can you use to ignore the value returned?
Use underscore (_)
Can you use range operators as switch cases?
Yes
case 1…10:
print(“numbers 1 to 10”)
What keyword can you use to exit loops immediately?
The “break” keyword
Can you give labels to loops (a.k.a “Label Statements”)?
Yes. with labelName followed by a colon
initialLoop: for-loop {}
Do you use the “break” keyword to skip the current iteration?
No. You use the “continue” keyword.
What is the difference between the “break” and “continue” keyword?
“break” exits out of the loop/s and “continue” skips to the next iteration.
What condition can you use to create an infinite-loop?
while true {}
What’s an example of a function?
func sayHello(name: String) -> String { print("Hello, \(name). Welcome!") }
sayHello(name: “Ruben”)
What is an “Expression?”
When a piece of code can be boiled to a single value.
e.g., true, false, “Hello, world”, 1337
What is a “Statement?”
When we’re performing actions such as: creating variables, starting loops, checking conditions
Are the following items an expression or statement?
3 > 1, true, false, “Boo”, 1010
Expression
Statement or expression?
let ans: Int = 100
Statement
Can you skip the “return” keyword when returning from a function if what you are returning is an expression?
Yes. but it has to be the only thing within the function. Function body cannot contain any statements
Is the “Ternary Operator” an expression or statement?
Expression
Is the “Ternary Operator” used in SwiftUI often?
Yes
Can a function return multiple values?
Yes. You using a tuple.
```
Example:
func makeRequest() -> (error: String, statusCode: Int) {
error: “ERROR”, statusCode: 200
}
~~~
Does Swift support an internal and external parameter label?
Yes, provide two labels. The first label is the external label, second is the internal label.
func sayHello(to name: String) -> { print("Hello, \(name).") }
sayHello(to: “Bob”)
Can you omit a function label?
Yes. Use the underscore (_) character in place the external parameter label
Is this code valid? If valid, what is the output?
func sayHello(to name: String = "Person") { print("Hello \(name). How are you?") }
sayHello()
Yes. Output is: “Hello Person, How are you?”
What is a “Variadic function?”
A function that accepts any number of parameters
Do variadic function parameters need to be of the same type?
Yes
Can you have multiple variadic parameters?
No. Only a single variadic parameter is permitted.
Is a variadic parameter converted to an array inside the function?
Yes
Can you pass an array to a variadic parameter in place of comma separated items?
No. It must be a list of comma separated items.
When creating a variadic parameter, what do you add following the input type?
Three dots (…)
func nums(list: Int…) {}
Can you throw structure instances?
Yes. Only use when Enums is not enough.
What keyword does a function definition need to declare that it could possibly return and error.
The “throws” keywords. Must be added before the return arrow symbol (->)
Exp: func saveFile(name: String) throws -> Bool { }
Is it possible to pass a parameter by reference so that it can be modified in place?
Yes. Use the keyword “inout” after the colon following the parameter label.
What kind of enum would you use if you want a case to have additional text associated with it?
Enum with associated values
What keyword do you use to raise an error?
The “throw” keyword
How do you explicitly show that you are passing a variable to a function as a reference instead of value?
Using an ampersand (&) before the variable name when calling a function.
When catching a thrown error, how do you print out the value associated with the associated value case statement?
catch Enum.caseWithValue(let message) {
print(“My associated msg: (message)”)
}
Do Enums and Structs must conform to input type “ThrowError” when used for throwing?
No. They must conform to an “Error” Input Type.
What is an example of a running a throwing function?
do { try functionThatThrows() } catch { }
When calling a function that expects an “inout” parameter do I have to do anything special?
Yes. use an ampersand (&) before the variable name.
var value = "My String" func(inOutParam: &value)
When passing parameters to functions are they immutable?
Yes. They cannot be modified. They are constants.
When should you mark a function parameter as an “inout” parameter?
When you want your function to modify the parameter inside the function.
What Array method can you use to remove an element from an array?
[].remove(at:) – Zero indexed
What 3 keywords rely on properly calling a throwing function?
“do”, “try” and “catch”
Inout parameters must be passed in using what symbol?
Ampersand (&) before the variable name.
Inout parameters are marked using what keyword?
“inout”
What mechanism can you use to return multiple parameters from a function?
Tuple; represented by open and closing parenthesis.
Exp: (One, Two, Three)
What Array method can you use to add items to the end of an array?
[].append(“last_item”)
Can you concatinate two arrays into one using the addition sign?
Yes.
[1,2,3] + [4,5,6] = [1,2,3,4,5,6]
How do you create an empty array of type Characters?
var letters = [Character]() or var letters = Array|Character|() or var letters: [Character] = []
What Array method can you use to count the number of elements?
[].count
Can a Set have duplicates?
No
Is the Array method [].remove(at:) zero indexed?
Yes
What Array method can you use to remove all items?
[].removeAll()
What Array method can you use to check if the array contains a certain element?
[].contains()
How do you return a new sorted array?
[].sorted()
What is thhe difference between an Array and a Set?
Sets are unordered and cannot contain duplicates, whereas arrays retain their order and can contain duplicates. Sets are highly optimized for fast retrieval than arrays.
When you reverse an array, does it actually reverse the array?
No. It returns a ReversedCollection type that when used will iterate in reverse. This is an optimization feature.
What method can you use to reverse an array?
[].reversed()
When checking if an item is included in a Set, can you use the “contains” keyword as you with Arrays?
Yes. set.contains()
When accessing an index that does not exist in an array, will it return an optional nil?
No. The application will crash.
How do you create an empty dictionary where the key type is an Int and the value type is a String
var agesToName = [Int: String]() or var agesToName = Dictionary|Int, String|() or var agesToName: [Int: String] = [:]
When retrieving a value from a dictionary, can you also provide a value in case that key does not exist in the dictionary?
Yes. dic[“myKey”, default: “NotFound”]
Can the default value of a dictionary retrieval be any type?
No, it must be the value type of the dictionary.
How do you count how many items are in a dictionary?
dic.count getter
How do you remove all items from a dictionary?
dic.removeAll()
When asking a dictionary for a value, do you get back an optional?
Yes, unless you explicitly set the default: parameter
Yes = dic["myKey"] No = dic["myKey", default: "NotFound"]
Are dictionaries more performant?
Yes, because the way they are stored and optimized allows for retrieval to be much faster than having to iterate over an array to find the value you want.
When adding items to a Set, can you use the “append” keyword as you do with Arrays?
No. You use set.insert(). “append” no longer makes sense because there is no actual order.
Can you sort a Set?
Yes. set.sorted()
How do you declare an empty Set?
var mySet = Set|String|() or var mySet: Set|String| = [] or var mySet: Set = ["one", "two", "three"]
When redefining a variable of type enum, do you always have to use the full EnumNameType.caseStatement?
No. once a variable is of type enum, you can simply use dot syntax.
exp:
var test = MyEnumType.hello
test = .goodbye
What is “Type Inference”?
When Swift infers the type of a variable or constant.
What is “Type Annotation”?
Let’s us be explicit about what data types we want.
Why is the following returning an error? What can you do to fix it it?
var num1 = 2 var num2 = 3.5
print(num1 + num2)
Swift is infering num1 as an Int and num2 as a Double. You cannot add two variables of different types.
There are multiple way to fix it: 1. Make num1 = 2.0, or cast num1 as a Double, or add type annotation to num1.
How do you create an empty array of strings?
var myArray = String
Should you always prefer Type annotation?
No. Prefer Type Inference and use Type annotation when necessary.
What is a good exception when Type annotation is preferred or required?
When you are declaring a constant that you don’t know the value yet.
Will this build?
let score: Int = “Zero”
No. Swift cannot convert the string “Zero” to an Int.
What value does Swift store?
var percentage: Double = 99
99.0
Why does Swift have type annotations?
- Swift can’t figure out what type should be used.
- You want Swift to use a different type from its default.
- You don’t want to assign a value just yet.
How do you create a new Set out of an existing array?
var newSet = Set(myOldArray)
What are the following called?
greater than, less than, ==, !=, greater than equal to, less than equal to
Comparison Operator Symbols
How do you remove the first element in an array?
myArray.remove(at: 0)
Can you use greater than and less than to compare two items of type ‘String’ ? If so, what does it do?
Yes. It will tell you if one is before the other in alphabetical order.
The following code checks if a variable of type String is empty. Is this the most performant? If not, then what is?
if myString.count == 0 { }
No. In Swift, unlike other languages, when getting the count Swift check every element and counts up. Better method is to use “isEmpty”
if myString.isEmpty { }
How are variables able to be compared using the Comparison operator?
Because the types conform to the “Comparable” Protocol.
Why does the following return true?
enum Sizes: Comparable { case small case medium case large }
let first = Sizes.small let second = Sizes.large print(first < second)
Because small comes before large in the enum case list.
Why would you add parenthesis in a if condition expression?
When using multiple conditions and you want to be explicit to Swift and developers what order the expression should be evaluated.
In Swift do Switches need to be exhaustive?
Yes. All cases need to be accounted for.
When writing a switch and you can’t possibly write down all cases, you can use an “else” case statement to define all other cases. Is this true?
No. You use the “default:” case
exp: switch thing { case one: print("Hi") default: print("All others") }
You have to be explicit in your case statements by adding a “break” statement at the end of each case or else it will continue to the next case down the list. Is this true?
No. It’s actually the other way around. After evaluation the correct switch statement Swift will stop evaluation the rest. If you want it to continue down the list. You must add the “fallthrough” statement at the end.
Can you use switch on an enum?
Yes. You must remember to account for every enum case. You must be exhaustive.
switch myEnum {
case .optionOne:
case .optionTwo:
}
What does it mean that switches must be exhaustive?
You must either have a case block for every possible value to check (e.g. all cases of an enum) or you must have a default case.
Does Swift require that its switch statements are exhaustive?
Yes
Why use a Switch statement instead of if/else if/else?
- Switches must be exhaustive, so you will avoid missing a specific case.
- Switch only checks the statement once, where as a condition might be written to check on every “else if” block.
- Switches allow for advanced pattern matching.
- When you have more than three conditions to check. Switch statements are often clearer to read than multiple if conditions.
Refactor the following code:
let test: String if true { test = "Must be true" } else { test = "Wrong!" }
Use the “Ternary Conditional Operator Expression”.
let test = true ? “Must be true” : “Wrong!”
What is a good Mnemonic for the Ternary conditional operator expression?
WTF ; What to test, True expression, False expression
How many pieces of input do Ternary conditional operators operate on?
Three. ; Thus the name Ternary
How many pieces of input do the following operate on: +, -, ==
Two. ; Thus the name Binary
Binary operators operate on how many pieces of input?
Two pieces of input
Ternary operators operate on how many pieces of input?
Three pieces of input
When using a loop, what do you call one cycle through the loop body?
A loop iteration
Is this valid code?
names = [“john”, “bob”]
for name of names {
print(“Hello!”)
}
print(name)
No. The loop variable is only available within the loop body.
In a for..in loop, what do you call the content between the braces?
The Loop Body
When you have nested loop and are counting, what is a common convention for the loop variable name?
First loop: (i), second inner loop: (j), third inner loop: (k). Any further you probably should pick different loop variable names.
How do you pronounce the range: 1…5
One through Five
How do you pronounce the range: 1..<5
One up to Five
What kind of range does the following create: x…y ?
Closed Range Operator: Starts at whatever the number x is, and counts up to and including whatever the number y is.
What kind of range does the following create: x..
Half-Open Range Operator: Starts at whatever the number x is, and counts up to and excludes whatever the number y is.
A range number always have two parts. The following will return an error. True or False?
names = ["john", "bob"] names2 = names[1...]
False. If you do not specify a second number in the range, it means start at x and continue until the end of the array.
When is the half-open range operator helpful when working with arrays?
When we count from 0 and often want to count up to but excluding the number of items in the array.
When are while loops useful?
When you just don’t know how many times the loop needs to go around.
How do you create a random number?
Int.random(in:) or Double.random(in:)
When are for loops useful?
When you have a finite amount of data to go through, for example, ranges, arrays or even Sets.