I’ve been playing around with Swift and going through Apple’s Language Guide for Swift. I created some quiz questions for myself based on the first chapter. These questions do not contain all the topics covered in the chapter. For example, booleans are excluded as I am comfortable using them.
All of these questions can be done using a XCode Playground. My answers are below the list of questions.
Declare a variable named ‘x’ and set it to 3
Declare a constant named ‘y’ and set it to 5
Declare a variable named ‘name’ of type String
Set the ‘name’ variable to Fred Flintstone
Print “hello” and your name
Represent the number 42 as a decimal, binary, octal and hexadecimal number. See Conversion Table - Decimal, Hexadecimal, Octal, Binary for conversion table.
Represent the number 1,500,000 as an exponential number
Sum these two variable: var a = 5 and var b = 0.25
Create a tuple containing a birth date (year, month and day) and then print those values
Using the birth date tuple created above get only the year and month and ignore the day
Create an optional variable named userInput of type String and set it to have no value
Set the userInput variable above to some value and use an if statement and forced unwrapping to print that value
Do the above step again but this time use optional binding instead of forced unwrapping
What is an implicitly unwrapped optional? When is it used?
Write an assert statement to check that a variable named ‘someVar’ is greater than 0.
1. We don’t need to declare a type as it is inferred from the value (In this case an Int)
11. An optional value says the variable has a value and it is X OR there is not a value.
14. Implicitly unwrapped optionals are written with an exclamation mark rather than a question mark (Double! vs Double?). They are used when it is clear the optional will always have a value. For example, the optional’s value is set immediately after declaring it. The following is an example.