Swift Docs: A Swift Tour Flashcards
What is a constant? How do we declare one?
Declare using let. Constants have their value set exactly once, but may be used many times. Constant values do not need to be known at compile.
What is a var? How do we declare one?
Declare using var. Vars may change, may be computed, and and do not need to be known at compile.
How does type inference work in Swift? How do you manually declare type?
Swift uses advanced type inference, so type declaration is not required unless the value is ambiguous to type (e.g. your value is 70.23, but you don’t want a double, you want a string).
Manually declare with var value: Double = 70.23
How do you type cast (explicitly convert to another type) in Swift? Cast name = “Dave” and value: Double = 70.23 into a single string.
”(name) has (String(value)) shares of Apple stock”
Swift offers a simpler way to cast a double or non string into a string. Use it to cast name = “Dave” and value: Double = 70.23 into a single string.
print(“(name) has (value) shares of Apple stock”)
How do we create a quotation in Swift? Supply code for “The only thing we have to fear is fear itself”.
Using double quotation marks at the beginning and end.
let quote = “””
The only thing we have to fear
is fear itself.
“””
How do we create an array in Swift? Create an array called shoppingList with Tomatoes, Beans, and Milk. Then add lemons to it as a second index element, and add bananas to it as the end index element.
We create using brackets, and, if we want to supply values, listing them inside.
var shoppingList = ["Tomatoes", "Beans", "Milk"] shoppingList[1] = "Lemons" shoppingList.append = "Bananas"
What is a dictionary, and how is it different but similar to an array?
Both Arrays and Dictionaries store series of values of like types. Arrays, however, index all values against a numerical index value starting at zero. Dictionaries allow you to specify Key/Value pairs, so you can customize the ‘key’ part of the equation.
Create a dictionary, called occupations, which stores Dave as Programmer, Sam as a banker, and Rick as a Marketer. Then add Evan as an engineer.
var occupations = [ //"Key": "Value" "Dave": "Programmer", "Sam": "Banker", "Rick": "Marketer" ]
occupations[“Evan”] = “Engineer”
Create an emptyArray and an emptyDict, both of type String
let emptyArray = String
let emptyDict = String: String
What is a For-In Loop? How do we use one to cycle through an array called dealValue?
For in allows us to programmatically cycle through values. For example, we could say “for x in dealValue…” which will use x to increment through the dealValue array.
What is a Switch? What is required to use one? Show how you’d cycle through it.
A switch allows you to define conditional logic based on 'cases'. For example we could say the following: let vegetable = "red pepper" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber", "watercress": print("That would make a good tea sandwich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup.") } Note you need a "default" case. It must be "exhaustive".
What is an optional, and what is the syntax? What is returned if an optional is not set at runtime?
An optional is an optional value - it allows you to invoke a var or let which may or may not be defined at runtime without destroying your app if it’s not set. If it’s not set, it returns nil. The syntax is let name: String? and then = the value it holds IF it is set.
What is the syntax for Optionals and Default Values? What is the logic here?
You use the optional first, followed by ??, followed by the default value;
print(“Hello, (nickname ?? realName)”), with nickname being the optional, and realName being the default value.
What data types do IF statements work with?
IF statements only work with equality comparisons and strings/ints. This is a nice aspect of switches, as they allow you to handle any kind of data type.
How do we use a For In loop with a dictionary, as opposed to any other value type?
Dictionaries are unique value types because they contain two value sets, keys and pairs. Normally with a for in loop we say “for x in y…”, but for a dict, we scan it using for (thing1, thing2) in y, where thing 1 is what you’re going to scan your keys with, and thing 2 being what you scan your values with.
How do we use a While loop? How can it be used in conjunction with Repeat, and how is this different from If?
While allows you to run syntax so long as a condition continues to be true. When we pair it with Repeat, and use While after the repeat logic, it lets us ensure the logic is run at least once.
Example: var z = 101 repeat { z *= 2 } while z < 100 print(z)
This will print 202. Because 101 will be multiplied by 2 once, since the while condition is after the logic. Alternatively, you can use it before the logic on its own:
Example: var x = 2 while x < 100 { x *= 2 } print(x)
This will print 128. The loop runs 6 times (4–>8–>16, so on).
What is the syntax to run a range UP TO the specified value, and what is the syntax to run a range INCLUDING the specified value?
Use “0..<3” to run a range of 0, 1, 2.
Use “0…3” to run a range of 0, 1, 2, 3.
How do we declare a function?
Use the func syntax, followed by parameters and their types in parenthesis separated by commas, and using an arrow to separate the parameters from the return type, followed by brackets.
“func functionName(parameter1: String, parameter2: Int) -> ReturnType { }”
Explain how functions can have internal and external parameter names, and the associated syntax. Also explain how you can have no external name for an argument.
We can specify a custom argument label before a parameter name in the parenthesis when defining a function. External name always comes first. You can also use _ to specify no external name.
func example(externalParamName internalParamName: String, _ secondParam: String)
In the above example, we’d use “internalParamName” and “secondParam” inside of the function’s code to reference our parameters, but we’d use “externalParamName” and blank while supplying the arguments in an external call to the func.
What exactly is the difference between parameters and arguments for a function?
Parameters are what you specify as inputs when defining a func, like func test(param: String)
Arguments are what you SUPPLY to the func when running it or passing it, like into a var. So I would pass an argument into “param” when using the function.
What is a Tuple? Write the syntax for a tuple with min, max, and sum.
A Tuple is a compound value, or, put another way, a means of extracting multiple returns from a function.
func math() -> (min: Int, max: Int, sum: Int) { }
What happens when functions are nested?
Functions can be nested inside of one another. A nested function can access the vars from its parent/external function.
func giveMe30() -> Int {
var z = 20 func addTen() { z += 10 } addTen() return z
}
What does Swift treating funcs as First Class Types mean?
First class types can be returned by a function. (like how a func can return a String, Int, Bool, etc). In Swift, Func is equivalent in type to any of these. So that means…functions can return other functions.
func firstClassFuncs() -> ((Int) -> Int) {
func increment(y: Int) -> Int {
var x = y x += 1 return x
} return increment
}
let number123 = firstClassFuncs() print(number123(10)) // prints "11"
Explain how functions can take funcs as arguments in Swift. What is the syntax for doing so?
In Swift, functions can both take funcs as arguments, and return funcs as returns. Syntax is identical to supplying a “regular” argument, you just list its name (e.g. passedFunc:) and then it’s arguments and returns (e.g. passedFunc: (Int) -> Bool
An example, where “condition” is a argument func.
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list { print(item) if condition(item) { return true } } return false
}
func greaterThan10(number: Int) -> Bool {
if number > 10 { return true } return false }
let array = [3]
hasAnyMatches(list: array, condition: greaterThan10)
What is a closure? Give an example.
Regarding other funcs and vars, what does a closure have access to as far as scope?
A block of code that can be called later. A function is an example of a closure.
Closures have access to any vars and funcs available at the scope where they are defined, even if the closure is run at a later time in a different scope. We saw this already with nested functions.