This repository contains set of questions for a self-check based on the book "The Swift Programming Language (Swift 3 beta)".
-
Do you need a main() funtion as an entry point for the programm in Swift?
Answer:
No, because global scope is used as an entry point itself.
-
How to declare constants and variables in Swift?
Answer:
You declare it with a keywords let and var like this:
var myVariable = 42 let myConstant = 42
-
Do you have to assign the value of the constant, when you declare it?
Answer:
The value of a constant can be assigned later, but you must to assign it a value exactly once.
-
How do you specify the type of constant or variable?
Answer:
You write the type after it's name, separated by colon, like this:
let explicitDouble: Double = 70
-
Will this code compile?
let label = "The width is " let width = 94 let widthLabel = label + width
Answer:
No, because label and width have different types. You need to convert it explicitly, like this:
let widthLabel = label + String(width)
-
What is the simpler way to include values in strings?
Answer:
You can use \() inside the string and put some value or calculation in parenthesis, like this:
let widthLabel = "The width is \(width) inches"
-
How do you create arrays and dictionaries? How do you access their elements?
Answer:
var colorsArray = ["red", "green", "blue"] colorsArray[1] = "yellow" var clothesDictionary = ["color": "blue", "size": "M"] clothesDictionary["size"] = "L"
-
What will this code do?
let const1 = [String]() let const2 = [String: Float]()
Answer:
It will create an empty array of Strings and empty dictionary, which keys are Strings and values are Floats.
-
Can you use this code to create empty arrays and dictionaries?
colorsArray = [] clothesDictionary = [:]
Answer:
Yes, but only if type information can be inferred.
-
What is wrong with this code?
var score = 1 if score print("Score isn't zero")
Answer:
Two things actually. First - in an if statement, the conditional must be a Boolean expression. Second - braces around the body are required. So, the code should look like this:
var score = 1 if score > 0 { print("Score isn't zero") }
-
What does ? after the type of value mean?
var myString: String? = "Hello"
Answer:
It means that a value is optional, i.e. it will contain nil if value is missing. If you assign nil to a value, which isn't optional, compiler will give you an error.
-
How to unwrapp optional value in an if statement and make it available inside the block of code?
Answer:
You can use if and let keywords together to unwrapp a value. If the optional value is nil, the conditional is false and the code in braces is skipped.
var optionalName: String? = "Bob" if let name = optionalName { print("Hello, \(name)") }
-
How to provide a default value when you work with optionals?
Answer:
You can provide default value using the ?? operator like this:
let optionalName: String? = nil print("Welcome, \(optionalName ?? "User")")
-
Can a switch statement contain more then one case, that match the value? If so, which one will be executed?
Answer:
Yes, it can. Switches support any kind of data and wide variety of comparison operations. For example, you can check if a value has full match with the other one in a case statement. Or check if it match with one of the listed options. Or check if it match the specific pattern you can specify with let and where keywords. If there are several cases that match the value, only the first one will be executed.
-
How do you iterate over items in a dictionary?
Answer:
One of the ways to do it is to use for-in statement, by providing a pair of names to use for each key-value pair:
let dict = ["key1": "value1", "key2": "value2"] for (key, value) in dict { print("key: \(key), value: \(value)") }
-
Swift has several operators to make loops. Which one ensures, that the loop will run at least once?
Answer:
repeat { print("This string will be printed at least once") } while false
-
How do you iterate an index over a range?
Answer:
Use ..< in a for-in loop to make a range that omits its upper value, and use ... to make a range, that includes both values.
for i in 0..<5 { // or 'for i in 0...5 {' print("index is: \(i)") }
-
How do you declare and call a function in Swift?
Answer:
Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate parameter names and types from the function's return type.
func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } greet(person: "Bob", day: "Tuesday")
-
How to modify a function from the answer to previous question, so that you can call it like this:
greet("Jhon", on: "Wednesday")
Answer:
By default, functions use their parameter names as labels for their arguments. Write _ to use no person argument label and write a custom label on before day parameter name:
func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." }
-
How to declare a function, that returns multiple values as a tuple? How to access the elements of a tuple?
Answer:
The elements of a tuple can be referred to either by name, or by number. A function, that returns a tuple can be declared like this:
func statsFor(array: [Int]) -> (min: Int, max: Int) { var min = array[0] var max = array[0] //... return (min, max) } let stats = statsFor(array: [1,2,3]) print("min: \(stats.min), max: \(stats.1)")
-
How to declare a function, that takes a variable number of arguments?
Answer:
Functions, that take a variable number of arguments, collect them into array. This kind of functions can be declared using ... after the type:
func sumOf(numbers: Int...) -> Int { var sum = 0 //... return sum } sumOf() sumOf(numbers: 1, 2, 3)
-
Does nested functions have access to variables that were declared in the outer functions?
Answer:
Yes.
-
How to declare a function that returns the following function as it's value?
func nestedFunc(argument: Int) -> Int { return argument*2 }
Answer:
func funcThatReturnsFunc() -> ((Int) -> Int) { func nestedFunc(argument: Int) -> Int { return argument*2 } return nestedFunc }
-
How to declare a function that takes the following function as an argument?
func argumentFunc(argument: Int) -> Int { return argument*2 }
Answer:
func funcThatTakes(function: ((Int) -> Int)) -> Bool { function(2) return true }
-
How do you separate an arguments and return type from a body of closure?
Answer:
You separate it using in keyword before body.
numbers.map({ (number: Int) -> Int in return number*2 })
-
In which case you can omit the parentheses in a function call like the one below? What does $0 and $1 mean?
let sortedNumbers = numbers.sorted { $0 > $1 }
Answer:
You can omit the parentheses of a function if closure is the only argument to it. $0 and $1 means you refer parameters of a closure by number instead of by name.
-
How do you declare a class with custom initializer, properties and methods? How do you create an instance of this class using custom initializer?
Answer:
You declare a class using class keyword and add an initialzer to it with init keyword like this:
class Person { var name: String var age: Int = 0 init(name: String, age: Int) { self.name = name // use 'self' to distinguish class property self.age = age // from initializer argument with the same name } func description() -> String { return "\(name), \(age)" } } // create an instance using custom initializer like this: var person = Person(name: "Bob", age: 42) person.description()
-
Will this code compile?
class User { var role: String = "User" var user_id: Int init(role: String) { self.role = role } }
Answer:
No, because of user_id property. Every property needs a value assigned - either in declaration (role) or in the initializer (user_id).