Fundamentals Flashcards

1
Q

Keyword to create an enumeration Type?

A

enum

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What type of syntax do you use to access enums?

A

dot syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can you use an enum in a switch statement?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you declare an enum with raw values?

A

enum ENUM_NAME: String {
case ENUM_CASE1 = “VALUE1”
case ENUM_CASE2 = “VALUE2”
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you declare an enum with associated values?

A
enum ENUM_NAME {
  case ENUM_CASE1(CASETYPE1)
  case ENUM_CASE2(CASETYPE2)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you access the value associated with an enum case in a switch statement?

A

case .ENUM_CASE(let VALUENAME):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What do you call variables within a Struct, Class?

A

Properties of a Struct, Class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Keyword to create different enumeration choices?

A

case

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Do you have to write initializers for Structs?

A

No. Swift will automatically create a “memberwise initializer”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Do all properties of a struct need to be declared when instantiating an instance of a structure?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What do you call the object created from a Struct/Class?

A

Instance of a Struct/Class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Are dictionaries ordered or unordered?

A

Unordered

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you access the enum’s raw value?

A

.rawValue getter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

When you declare a variable as an enum type and you are setting it, can you use a shorter syntax?

A

Yes, use dot syntax. (exp: .caseItem)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you declare and initialize a dictionary using a literal format?

A

var DICT = [
“KEY1”: “VALUE1”,
“KEY2”: “VALUE2”
]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What do you call functions within a Struct, Class?

A

Methods of a Struct, Class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Are “switch case” statements labels capitalized?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you force unwrap optionals?

A

Using the bang (!) symbol after a variable name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

When you set the value of a dictionary key to nil, does it remove it from the collection?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you declare and initialize an empty dictionary of type String: Int

A

var DICT: [String: Int] = [:]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What method can you call that returns a tuple containing an index and the value?

A

array.enumerated()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

When Iterating a dictionary, could you get a different order of items?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When getting the value of a dictionary does it return an optional value?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What keyword do you use to define a tuple?

A

Parenthesis (ITEM1, ITEM2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
When a function returns a tuple can you define the labels associated with it?
``` Yes func MYFUNC() -> (LABEL1: String, LABEL2: Int) { } ```
26
When creating an enum is it a Type?
Yes
27
Can you nest Enums within a Struct?
Yes. When accessing from outside of Struct, full path is required Exp. Struct.Enum.case
28
Can you use a function as a closure?
Yes, but it's a code smell if you are not using it somewhere else.
29
Can you use index notation to access a specific tuple?
Yes
30
When you don't label your closure function variables, are they still accessible?
Yes. $0, $1, $2 ...
31
How do you decompose a tuple? into variables
let (FIRST, SECOND) = (1, 2)
32
I want to sort an array in place what method can I use?
array.sort(by:) { }
33
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 }
34
What String method can you use to return a Bool if string ends with certain characters?
"".hasSuffix("ending")
35
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
36
How do you map over an array
array.map(transform:) { (item) in ... }
37
Can you break up tuples using nested arrays into variables?
Yes.. Exp: | let (key, (value1, value2) = $0
38
What affect does adding underscores when storing a whole number have?
None. Swift ignores them
39
What method can you use to iterate over all items in a collection?
list.forEach(body:) { (item) in ... }
40
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.
41
I want to sort an array without modifying the calling array, How do I do that?
let newArray = array.sorted(by:) { }
42
How you create a multi-line strings?
Use triple quotes to start and end multi-line strings var text = """ Text """
43
Can you add Emoji's in a string?
Yes
44
How do you count the characters in a string?
use .count getter
45
What String method can you use to uppercase the characters?
.uppercased()
46
What String method can you use to get a Bool if string starts with certain characters?
"".hasPrefix("beginning")
47
When storing long numbers, is it possible to break them down using comma's?
No, but you can break them up using underscores instead.
48
Does Swift support shorthand operators?
Yes. count += 1 ; count -= 1
49
What Int method can you use to get a Bool if integer is multiple of something?
120.isMultiple(of: 3)
50
What Bool method can you use to flip a boolean to the opposite value?
.toggle() ``` exp: var isOpen = true ``` isOpen.toggle()
51
What is a "Half-open Range Operator?"
1..<10 - Range between 1 and 10 excluding the last number, so 1-9.
52
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
53
What is a "Compound Assignment Operator?"
Syntactical sugar for var = var + 1 var += 1
54
What affect does using "Comparison operators" on two strings?
Compares if they are in alphabetical order
55
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"
56
Example of a condition statement?
if a > 1 { } else if a < 1 {} else {}
57
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.
58
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.
59
When building a conditional with multiple expressions, should you use parenthesis?
Yes. Specially if expression includes an OR expression
60
What is the "Ternary Operator?"
let answer: String = true ? "True" : "False"
61
When creating a switch statement, do you need to have a default case?
Yes. all cases must be exhaustive!
62
What is a "Closed Range Operator?"
1...10 - Range between 1 and 10 including the last number, so 1-10
63
How do you write a while loop?
while count <= 20 { count += 1 }
64
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 } }
65
How do you know to use for .. in or while loops?
For ... in loop = Finite sequences | While loop = Unknown amount of sequences
66
When should you use the repeat {} while loop?
When you want your condition to execute at least once before checking the condition.
67
Example of repeat {} while
``` let numbers = [1, 2, 3, 4, 5] var random: [Int] ``` repeat { random = numbers.shuffled() } while random == numbers
68
What Array method can you use to create, and shuffle a new copy of an array?
[].shuffled()
69
What character can you use to ignore the value returned?
Use underscore (_)
70
Can you use range operators as switch cases?
Yes case 1...10: print("numbers 1 to 10")
71
What keyword can you use to exit loops immediately?
The "break" keyword
72
Can you give labels to loops (a.k.a "Label Statements")?
Yes. with labelName followed by a colon initialLoop: for-loop {}
73
Do you use the "break" keyword to skip the current iteration?
No. You use the "continue" keyword.
74
What is the difference between the "break" and "continue" keyword?
"break" exits out of the loop/s and "continue" skips to the next iteration.
75
What condition can you use to create an infinite-loop?
while true {}
76
What's an example of a function?
``` func sayHello(name: String) -> String { print("Hello, \(name). Welcome!") } ``` sayHello(name: "Ruben")
77
What is an "Expression?"
When a piece of code can be boiled to a single value. e.g., true, false, "Hello, world", 1337
78
What is a "Statement?"
When we're performing actions such as: creating variables, starting loops, checking conditions
79
Are the following items an expression or statement? 3 > 1, true, false, "Boo", 1010
Expression
80
Statement or expression? let ans: Int = 100
Statement
81
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
82
Is the "Ternary Operator" an expression or statement?
Expression
83
Is the "Ternary Operator" used in SwiftUI often?
Yes
84
Can a function return multiple values?
Yes. You using a tuple. | ``` Example: func makeRequest() -> (error: String, statusCode: Int) { error: "ERROR", statusCode: 200 } ```
85
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")
86
Can you omit a function label?
Yes. Use the underscore (_) character in place the external parameter label
87
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?"
88
What is a "Variadic function?"
A function that accepts any number of parameters
89
Do variadic function parameters need to be of the same type?
Yes
90
Can you have multiple variadic parameters?
No. Only a single variadic parameter is permitted.
91
Is a variadic parameter converted to an array inside the function?
Yes
92
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.
93
When creating a variadic parameter, what do you add following the input type?
Three dots (...) func nums(list: Int...) {}
94
Can you throw structure instances?
Yes. Only use when Enums is not enough.
95
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 { } ```
96
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.
97
What kind of enum would you use if you want a case to have additional text associated with it?
Enum with associated values
98
What keyword do you use to raise an error?
The "throw" keyword
99
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.
100
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)") }
101
Do Enums and Structs must conform to input type "ThrowError" when used for throwing?
No. They must conform to an "Error" Input Type.
102
What is an example of a running a throwing function?
``` do { try functionThatThrows() } catch { } ```
103
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) ```
104
When passing parameters to functions are they immutable?
Yes. They cannot be modified. They are constants.
105
When should you mark a function parameter as an "inout" parameter?
When you want your function to modify the parameter inside the function.
106
What Array method can you use to remove an element from an array?
[].remove(at:) -- Zero indexed
107
What 3 keywords rely on properly calling a throwing function?
"do", "try" and "catch"
108
Inout parameters must be passed in using what symbol?
Ampersand (&) before the variable name.
109
Inout parameters are marked using what keyword?
"inout"
110
What mechanism can you use to return multiple parameters from a function?
Tuple; represented by open and closing parenthesis. Exp: (One, Two, Three)
111
What Array method can you use to add items to the end of an array?
[].append("last_item")
112
Can you concatinate two arrays into one using the addition sign?
Yes. [1,2,3] + [4,5,6] = [1,2,3,4,5,6]
113
How do you create an empty array of type Characters?
``` var letters = [Character]() or var letters = Array|Character|() or var letters: [Character] = [] ```
114
What Array method can you use to count the number of elements?
[].count
115
Can a Set have duplicates?
No
116
Is the Array method [].remove(at:) zero indexed?
Yes
117
What Array method can you use to remove all items?
[].removeAll()
118
What Array method can you use to check if the array contains a certain element?
[].contains()
119
How do you return a new sorted array?
[].sorted()
120
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.
121
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.
122
What method can you use to reverse an array?
[].reversed()
123
When checking if an item is included in a Set, can you use the "contains" keyword as you with Arrays?
Yes. set.contains()
124
When accessing an index that does not exist in an array, will it return an optional nil?
No. The application will crash.
125
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] = [:] ```
126
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"]
127
Can the default value of a dictionary retrieval be any type?
No, it must be the value type of the dictionary.
128
How do you count how many items are in a dictionary?
dic.count getter
129
How do you remove all items from a dictionary?
dic.removeAll()
129
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"] ```
131
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.
132
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.
133
Can you sort a Set?
Yes. set.sorted()
134
How do you declare an empty Set?
``` var mySet = Set|String|() or var mySet: Set|String| = [] or var mySet: Set = ["one", "two", "three"] ```
135
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
136
What is "Type Inference"?
When Swift infers the type of a variable or constant.
137
What is "Type Annotation"?
Let's us be explicit about what data types we want.
138
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.
139
How do you create an empty array of strings?
var myArray = [String]()
140
Should you always prefer Type annotation?
No. Prefer Type Inference and use Type annotation when necessary.
141
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.
142
Will this build? let score: Int = "Zero"
No. Swift cannot convert the string "Zero" to an Int.
143
What value does Swift store? var percentage: Double = 99
99.0
144
Why does Swift have type annotations?
1. Swift can’t figure out what type should be used. 2. You want Swift to use a different type from its default. 3. You don’t want to assign a value just yet.
145
How do you create a new Set out of an existing array?
var newSet = Set(myOldArray)
146
What are the following called? greater than, less than, ==, !=, greater than equal to, less than equal to
Comparison Operator Symbols
147
How do you remove the first element in an array?
myArray.remove(at: 0)
148
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.
149
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 { }
150
How are variables able to be compared using the Comparison operator?
Because the types conform to the "Comparable" Protocol.
151
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.
152
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.
153
In Swift do Switches need to be exhaustive?
Yes. All cases need to be accounted for.
154
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") } ```
155
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.
156
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: }
157
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.
158
Does Swift require that its switch statements are exhaustive?
Yes
159
Why use a Switch statement instead of if/else if/else?
1. Switches must be exhaustive, so you will avoid missing a specific case. 2. Switch only checks the statement once, where as a condition might be written to check on every "else if" block. 3. Switches allow for advanced pattern matching. 4. When you have more than three conditions to check. Switch statements are often clearer to read than multiple if conditions.
160
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!"
161
What is a good Mnemonic for the Ternary conditional operator expression?
WTF ; What to test, True expression, False expression
162
How many pieces of input do Ternary conditional operators operate on?
Three. ; Thus the name Ternary
163
How many pieces of input do the following operate on: +, -, ==
Two. ; Thus the name Binary
164
Binary operators operate on how many pieces of input?
Two pieces of input
165
Ternary operators operate on how many pieces of input?
Three pieces of input
166
When using a loop, what do you call one cycle through the loop body?
A loop iteration
167
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.
168
In a for..in loop, what do you call the content between the braces?
The Loop Body
169
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.
170
How do you pronounce the range: 1...5
One through Five
171
How do you pronounce the range: 1..<5
One up to Five
172
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.
173
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.
174
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.
175
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.
176
When are while loops useful?
When you just don’t know how many times the loop needs to go around.
177
How do you create a random number?
Int.random(in:) or Double.random(in:)
178
When are for loops useful?
When you have a finite amount of data to go through, for example, ranges, arrays or even Sets.