Ultimate Ios 10, Xcode 8 Development Book: Build 30 Apps
By John Bura, Razvan Nesiu, Alexandra Kropova and
()
About this ebook
The code in this book is easy to follow along with. The book's numerous screenshots ensure that no learner is left behind.
Playground – In Part 1, you learn the foundations of Xcode using Swift 3.0's Playground. The Playground is the perfect place to test code in real-time. We use the Playground to introduce coding topics like variables, functions, and loops.
UI Elements – Apps are made up of User Interface (UI) elements. In Part 2, you create Projects to test common UI elements, including labels, buttons, and text fields. With code, you learn to implement the objects to give them functionality.
Example Apps – In Part 3, we create functioning apps. To build an app, we design its layout and implement its functionality. You learn how to test your apps by running them in the Simulator.
Read more from John Bura
Build 6 Games In Unreal Rating: 0 out of 5 stars0 ratingsBuild a 3d Virtual Reality Whackamole Game Rating: 0 out of 5 stars0 ratingsLearn Css In 1 Hour Rating: 0 out of 5 stars0 ratingsIntroduction to Unreal Rating: 0 out of 5 stars0 ratingsLearn Javascript In 1 Hour Rating: 0 out of 5 stars0 ratingsIntroduction to Unity Rating: 0 out of 5 stars0 ratingsConstruct 2 Game Development by Example Rating: 0 out of 5 stars0 ratingsLearn Html In 1 Hour Rating: 0 out of 5 stars0 ratings
Related to Ultimate Ios 10, Xcode 8 Development Book
Related ebooks
Swift 3 Object-Oriented Programming - Second Edition Rating: 0 out of 5 stars0 ratingsPrezi HOTSHOT Rating: 0 out of 5 stars0 ratingsGoogle Apps Script Standard Requirements Rating: 0 out of 5 stars0 ratingsjQuery Game Development Essentials Rating: 0 out of 5 stars0 ratingsOuya Unity Game Development Rating: 0 out of 5 stars0 ratingsTwilio Cookbook: Second Edition Rating: 0 out of 5 stars0 ratingsLearning Bing Maps API Rating: 0 out of 5 stars0 ratingsLearn Programming by Coding Like a Professional: Create Games, Apps, & Programs Rating: 0 out of 5 stars0 ratingsJavaScript Interview Questions You'll Most Likely Be Asked: Job Interview Questions Series Rating: 0 out of 5 stars0 ratingsTeach Yourself Programming The Guide to Programming & Coding Like a Professional Rating: 0 out of 5 stars0 ratingsMission JavaScript Rating: 0 out of 5 stars0 ratingsLearn Programming Using C# Rating: 0 out of 5 stars0 ratingsC# Interview Questions You'll Most Likely Be Asked Rating: 0 out of 5 stars0 ratingsPython. Easy Steps to Learning. Rating: 0 out of 5 stars0 ratingsExcel VBA: A Beginners' Guide Rating: 4 out of 5 stars4/5Vb Net Programming Rating: 0 out of 5 stars0 ratingsJava: Best Practices to Programming Code with Java Rating: 0 out of 5 stars0 ratingsJava: Best Practices to Programming Code with Java: Java Computer Programming, #3 Rating: 0 out of 5 stars0 ratingsThe Little Book of Javascript Rating: 0 out of 5 stars0 ratingsJavaScript: Advanced Guide to Programming Code with JavaScript Rating: 0 out of 5 stars0 ratingsJavaScript: Advanced Guide to Programming Code with Javascript: JavaScript Computer Programming, #4 Rating: 0 out of 5 stars0 ratingsJavascript - 50 functions and tutorial Rating: 0 out of 5 stars0 ratingsProgramming with Python Rating: 0 out of 5 stars0 ratingsJust the basics of JavaScript Rating: 0 out of 5 stars0 ratingsThe Complete Friday Q&A: Volume III Rating: 0 out of 5 stars0 ratingsAdvanced C++ Interview Questions You'll Most Likely Be Asked Rating: 0 out of 5 stars0 ratingsCORE JAVA Interview Questions You'll Most Likely Be Asked Rating: 4 out of 5 stars4/5Python An Introduction Rating: 0 out of 5 stars0 ratingsGo Programming Language For Dummies Rating: 0 out of 5 stars0 ratings
Computers For You
The Invisible Rainbow: A History of Electricity and Life Rating: 4 out of 5 stars4/5101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 5 out of 5 stars5/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 0 out of 5 stars0 ratingsDark Aeon: Transhumanism and the War Against Humanity Rating: 5 out of 5 stars5/5Elon Musk Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 0 out of 5 stars0 ratingsCompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsThe Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5The Mega Box: The Ultimate Guide to the Best Free Resources on the Internet Rating: 4 out of 5 stars4/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5CompTIA Security+ Practice Questions Rating: 2 out of 5 stars2/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5ChatGPT Ultimate User Guide - How to Make Money Online Faster and More Precise Using AI Technology Rating: 0 out of 5 stars0 ratingsThe Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling Rating: 0 out of 5 stars0 ratingsUltimate Guide to Mastering Command Blocks!: Minecraft Keys to Unlocking Secret Commands Rating: 5 out of 5 stars5/5Practical Lock Picking: A Physical Penetration Tester's Training Guide Rating: 5 out of 5 stars5/5
Reviews for Ultimate Ios 10, Xcode 8 Development Book
0 ratings0 reviews
Book preview
Ultimate Ios 10, Xcode 8 Development Book - John Bura
The Ultimate iOS 10, Xcode 8 Development Book: Build 30 Apps
by John Bura, Nimish Narang, Razvan Nesiu, and Chris Veillette
Copyright
Copyright © 2017 Mammoth Interactive, Inc. All rights reserved.
Printed in Canada.
Published by Mammoth Interactive, Inc., 218 – 111 West Broadway, Vancouver, British Columbia, Canada V5Y 1P4.
Mammoth Interactive books may be purchased for educational, business, or sales promotional use.
Content Creators: John Bura, Nimish Narang, Razvan Nesiu, and Chris Veillette
Transcriber/Editor: Alexandra Kropova
March 2017: Second Edition
About the Author
John Bura has been programming since 1997 and teaching since 2002. John brings a unique perspective with his years of experience of teaching and real-world experience running a software company. In 2008, John founded Mammoth Interactive.
Since then, his company has sold over 400,000 copies of educational courses around the world. Mammoth Interactive's courses have been featured on websites such as Venture Beat, Expert Dojo, Cult of Mac, and Macgams. In addition, Mammoth Interactive has produced games for the iPhone, iPad, XBOX 360, and more.
John and his company have a history of supporting other developers. Mammoth Interactive has been contracted to produce epic soundtracks, addicting levels, rock-solid programming, and business development.
Over 300,000 students have enrolled in Mammoth Interactive. And they love it. Go to www.mammothinteractive.com to get free stuff, courses, books, apps, games, t-shirts, daily deals, and more!
www.mammothinteractive.com
PART 1: Playground
This book covers elements of the Swift 3.0 programming language using Xcode Version 8.0 beta 2. Xcode contains software development tools for creating iOS applications.
To follow along with Part 1's examples, open Xcode and select Create a New Playground
. The default screen of the Playground file contains the following code:
//: Playground — noun: a place where people can play
import UIKit
var str = Hello, playground
The preceding code defines Playground
, imports the UIKit, and declares a string variable. Swift 3.0's Playground is an environment where you can write and test code. The Playground is useful for experimenting with code rather than doing application development. App development requires a different type of Xcode file.
Playground allows you to write and test your code without having to create an app. The great thing about Playground is that it runs often, compiling the code so that you can see the results of your coding in real-time.
We will use the Playground file to introduce the different components of Xcode listed in this book's table of contents. This book includes real-life, practical examples that you may encounter as a programmer. Ready to begin?
CHAPTER 1: Variables
A variable is an object in Xcode that can have a name, type, and value. Once you assign a variable a name or type, you cannot alter those properties with new code. To do so, you would have to convert the variable into a new one.
However, the value of a variable can be changed. As the name implies, variables are variable. On the other hand, the value of a constant, a type of object covered in this chapter, cannot be changed.
To set up a variable, use the keyword var. Select var - Swift Var Declaration, which refers to a Swift variable declaration. The following code will appear on your screen:
var name = value
Do not worry about errors that may appear on the screen. They appear merely because we have yet to give our new variable a name or value. In the following code, variable_name is the placeholder for the variable's name. : Type is the format for setting the variable type. variable_value is the placeholder for the variable's value.
var variable_name : Type = variable_value
You can choose whether to give a variable a type or value. However, a variable must have a name. As well, if you do not specify the type, the compiler will automatically assume the type based on the variable's value.
For example, if a variable's value is 1 or 2, the variable will automatically take on the type Integer. If the value is Hello
, the variable will take on the type string. If the value is a Boolean value, the variable will take on the type Boolean.
You do not always need to specify type if you specify value. Likewise, you do not always have to specify the value if you specify type. Thus variables can be declared in multiple ways:
var name1 : Type
var name2 = value
var name3 : Type = variable_value
The first variable in the preceding code has a type, the second has a value, and the third has both a variable and a value. You must always follow one of those conventions. Note that, in Playground, the variable name1 is labeled as an error because Type is not an actual variable type. If you make name1 of the type Integer (Int), the error will disappear:
var name1 : Int
IDEA If you do not give a variable a value and then attempt to use it later on in the code, you will probably see an error saying that the variable does not contain a value.
There are many different types of variables. The common types covered in this book are: Booleans, integers, floats, doubles, strings, and characters.
Booleans are either true or false variables. Integers, floats, and doubles are number representations. Strings are used for texts and messages. Characters like strings but of length one (single-unit items).
Booleans
In this section, we will introduce the variable and constant type Boolean. Constants are similar to variables except that they cannot change their values. If you have an item that you know will never need to change, declare it a constant. If you think the item might change, make it a variable.
A constant can still have a type and a value. Constants are called with the keyword let:
let name = value
To remain consequential, name the constant name4.
let name4 = value
A Boolean constant (or variable) contains either the value true or false. Thus a Boolean can have one of two states. The type Boolean is useful for variables that only take on one of two values. As well, Booleans are useful for running tests.
To create a Boolean, open a new Playground file. Below the existing variable Hello, playground
, create a new variable named isTrue, and declare it of type Boolean. When you type Bool
, a drop-down menu pops up that contains several suggestions for variable type. Select the topmost one: Bool (short for Boolean). Furthermore, initialize the variable to be true. Your line of code should look like the following:
var isTrue : Bool = true;
Create another variable named isFalse that is of type Boolean and has the value false.
var isFalse : Bool = false;
In Playground, the code you create is automatically tested. The right-hand sidebar displays the results. Currently, you should see the words true
and false
in the sidebar.
Let's see what happens if we try to give a Boolean variable a value that is not a Boolean. For instance, create a Boolean variable named different_bool, and set it equal to 5.
var different_bool : Bool = 5;
An error will appear. If you click on the line of code, you can read the error: Cannot convert of type 'Int' to specified type 'Bool'.
This proves that Booleans can only contain true or false values.
To correct the error, you could change 5 to true. Alternatively, you could remove : Bool. Then the compiler would automatically assign different_bool the type Integer because of the value 5. However, including the type is recommended until you feel comfortable with variable types.
We just created a Boolean variable. We can also create Boolean constants. To do so, use the keyword let. Let's name our constant constant_bool and give it the type Boolean and value false.
let constant_bool : Bool = false;
The compiler will print false
.
As mentioned, the difference between the constants and the variables is that the variables can be re-assigned. Variables can take on different values. Constants, once declared, can only contain that one value. To prove this, on a new line, we can re-assign different_bool the new value false.
different_bool = false
The compiler will print false
. If you call the variable again on a new line, the compiler will again print false
:
different_bool
On the other hand, if we try to re-assign the value true to the Boolean constant, an error message will appear saying that you cannot re-assign the values of constants.
constant_bool = true
IDEA You can choose whether to include semi-colons at the end of each line of code, although it is not necessary in Swift 3.0. Other coding languages require a semi-colon at the end of every line. In Swift 3.0, you can use semi-colons to separate different statements that you want to all appear on one line.
There is another way to assign Booleans a value. Rather than giving it the value true, you can write a statement that is true, such as the following:
var trueStatement : Bool = (5==5)
In Xcode, the double equals sign (==) is used for comparison. In the preceding code, it means: Is 5 equal to 5?
The single equals sign (=) is used for assignment. It means: This variable is equal to this value.
Then, if you call the trueStatement variable on a new line, the compiler will print true
because we assigned the variable to be a true statement.
trueStatement
There is a similar alternative for assigning a Boolean variable the value false:
var falseStatement : Bool = (4==7)
Call the variable by writing falseStatement on a new line. The text false
will appear in the right sidebar.
To summarize: you can assign values to Boolean variables in two ways:
explicitly state true or false
implicitly assign it the value true or false by writing a true or false statement
Let's look at an example of where we might see Booleans in real life. Some compilers recognize Boolean variables as binary numbers (0 or 1). For instance, the C++ compiler prints a false Boolean as 0 and a true Boolean as 1.
A real-life example of Boolean variables is an account which cannot be accessed until a Boolean variable equals true. Suppose an account has credentials such as a username or password that a user can enter. The user can log into the account only by entering the correct credentials.
To code this example, first create the Boolean variable isLoggedIn. Initialize it to be false.
var isLoggedIn : Bool = false
The preceding line of code means that the user is not logged in and therefore cannot access their account. The compiler will print false
. However, when the variable becomes true (when the owner enters the correct credentials), the compiler will print true
. The user will be able to access their account.
isLoggedIn = true
Another example of Booleans in code is the programming of an elevator that does not move until a Boolean variable equals true. To demonstrate this, create the new variable isDoorClosed. Assign it the type Bool and the value true.
var isDoorClosed : Bool = true;
Suppose the elevator is programmed to not move if its doors are open. The elevator only starts moving once the doors are closed. But how does the programming of the elevator determine whether the doors are closed? Perhaps the value of isDoorClosed can only change when sensors sense that the elevator door is fully closed. Thus the elevator will not move until the variable is changed from false to true.
Integers
In this section, we will discuss the different values an integer can have. Furthermore, we will look at examples of where we would use integers rather than other number variable types.
What exactly are integers? As you may vaguely recall from high school math, integers are numbers that are negative, positive, or zero. They must be whole numbers. They cannot have decimal places. For instance, -5 is an integer, but -5.5 is not. 5.5 can be either a float or a double, which we will cover in a later section.
Let's begin immediately with an example. With the following code, declare the variable first_int of type Integer and with a value of 7. The compiler will print 7
.
var first_int : Int = 7
When you write Int
to declare the type of variable, different types of integers appear in a pop-up. We will be using the first one in the list: Int. The other types are used in different scenarios, such as passing data or using a specific function.
Changing between types of integers is simple. For instance, to change first_int's type to Int32, write the following code on a new line. With this format, the compiler will print 7
again, but the integer will be of type Int32.
Int32(first_int)
Just as you can to Booleans, you can re-assign values to integers. For first_int to contain the value 20 rather than 7, simply add the following line:
first_int = 20
However, like with Booleans, if you create an integer constant, you cannot change its value on a new line. For instance, you cannot add a new line to change the following constant's value from -3.
let constant_int : Int = -3
Next we will look at some operations that we can perform with integers. Because integers are numbers, we can perform many different operations, including addition, subtraction, multiplication, and division. To try using operations, create some new integers:
var a : Int = 5
var b : Int = -15
To perform addition on variables a and b, simply write:
a + b
-10
will print because that is the result of 5 + -15
. The line a - b will produce 20
. a * b will produce -75
. b / a will produce -3
.
While we can perform many operations like these, some built-in functions, such as the power function, require Double variables, which are numbers with decimal places. Therefore, to perform some operations, we must convert the variable type. To make variable a a Double variable, for example, add:
Double(a)
There are some exceptions to converting variables. For instance, you cannot convert a Boolean to an integer because the values true
and false
do not contain numbers. What if you attempted to assign a Double value to an integer? Try coding this:
var c : Int = 6.6
An error message will appear saying Cannot convert 'Double' to an Integer
. So, what happens if one of our operations has a result that is a decimal number? Let's find out. Give variable c the value 6, and try dividing c by a.
var c : Int = 6
c/a
Although 6 divided by 5 is 1.2, the compiler will print 1
. The result has to be an integer because our operation was performed on integers. Unlike Swift 3.0, many other programming languages will give you an error message as the result of such an operation.
Now for some real-life examples. Our first example is of a character moving around in a video game. For this scenario, declare the following variable:
var position : Int = 0
Furthermore, create some constants:
let movement1 : Int = 6
let movement2 : Int = -8
Integers effectively represent movements because characters rarely take a half-step or third-step. In most cases, video game characters will take steps one tile at a time. Therefore, you can set a character's position by performing an operation such as addition:
position = position + movement1
6
will appear on the screen, which is the result of 0 + 6
. This means that the final position of the character will be its initial position plus its first movement. If you were to print out position now by writing position on a new line, the compiler would print out 6
.
We can perform a similar operation with movement2 to achieve a position of -2
.
position = position + movement2
Integers are useful for games that involve a player's having lives
because the lives are often counted with whole numbers. If you know that a number will be a whole number, it is best to use integers because they take up less memory and are faster to deal with than other number types. If your numbers contain decimals, use floats or doubles, or convert the integers to Doubles when needed.
Floats and Doubles
We will discuss the difference between floats and doubles, as well as where to use them in code. Additionally, we will go over where these variable types need to be used rather than integers.
Floats and doubles are two different ways to represent decimal numbers. The difference between the two is that doubles provide about twice the precision of floats. Specifically, floats can contain up to 7 digits. The following is a float named float1. It is of type Float and has the value 5.5.
var float1 : Float = 5.5
If you try to add more digits to the value of float1, either to the left or to the right of the decimal place, the compiler will only print out the first 7 (reading from the left). For some large numbers, the number will be shown in scientific notation. For example, the next example float will be displayed in the right sidebar as 5.555556e+08
.
var float2 : Float = 555555555.55555555
Doubles differ. Decimal numbers default to be doubles. The following are doubles:
var double1 : Double = 6.6
var double2 : Double = 6.66666666666666
As you can see, the compiler prints doubles with an accuracy of up to 14 decimal places. If there are more digits before the decimal place, the compiler will print at least 2 of those and up to 12 decimals. However, you will rarely need this kind of precision.
Doubles are useful for representing extremely large or small numbers. Floats are better used for numbers with fewer decimal places where you do not need to be as precise. For example, with money. Monetary amounts usually have two decimal places, so their values are better represented as floats. On the other hand, numbers such as the sizes of planets are better represented with doubles.
As mentioned previously, many built-in math functions can take in only doubles as parameters. Whenever you call a built-in function, check the types of numbers it inputs. You may need to convert your integers or floats to doubles. For example, to make float1 a double, type:
Double(float1)
An example of floats in everyday life is in the transactions of a bank account. To try out this example, create the following variables and constants. Regarding the withdrawal constant, make sure not to have a space between the negative sign and the number.
var bank_balance : Float = 0
let deposit : Float = 500.50
let withdrawal : Float = ‒223.98
In this scenario, a bank account owner makes a deposit and a withdrawal. The owner then wants to know their account balance. Code the following:
bank_balance + deposit + withdrawal
The bank balance will show up in the right-hand sidebar: 276.52.
You can use substitute doubles for floats, but not always vice-versa because doubles are more precise than floats. An operation can contain either floats or doubles, but not both. To see that the previous operation would result in an error if you mixed types, change the float bank_balance to a double.
var bank_balance : Double = 0
To correct the error, you can change the variable type within the existing operation:
Float(bank_balance) + deposit + withdrawal
Characters and Strings
Characters and strings can contain numbers, letters, or symbols. In Swift 3.0, they can even contain emoji's! Characters are only one unit in length. Strings, on the other hand, have no limit in length. We will first demonstrate characters by creating some variables:
var a : Character = a
var b : Character = 1
var c : Character = $
In Swift 3.0, the values of characters and strings are written in double quotations. You may also notice that the values of the characters we created are all one unit long, as is allowed for characters. To insert an emoji in the quotation marks, go to Edit > Emojis & Symbols.
Declaring a string is similar to declaring a character:
var string1 : String = mammoth
Strings can be thought of as an array of characters. In the preceding box of code, string1 contains seven characters. If we tried to convert string1's type to Character, we would receive an error message. You can change a character to a string, but you cannot change a string (with more than one unit) to a character.
You can also combine strings like this:
var string1 : String = mammoth
var string2 : String = interactive
string1 + string2
From the preceding code, the compiler will print mammoth interactive
. This is called appending.
To make string1 equal the combined value of it and string2, either type:
string 1 = string1 + string2
or
string1 += string2
The second option is a shortcut that can save time if you have to re-assign values to many strings.
In languages such as C, strings do not exist. Instead, you have to use lists of characters. Strings are particularly useful for displaying messages or text within code. Generally, print statements will take in only strings. Therefore, you have to convert text being printed to type String.
The compiler reads values expressed in quotations as strings. The value of variable b contains the number 1. Though this is a number, the variable would be interpreted as a character had we not specified the type.
Also note that you can have empty strings, as demonstrated in the following box of code, but NOT empty characters.
var string3 : String =
You cannot convert characters to integers. If you try to convert b to an integer by writing the following line, an error message will appear.
Int(b)
You CAN convert strings to integers, provided that the strings contain numerical values. To prove it, declare a new string and try to convert its type.
var string_to_int : String = 2
Int(string_to_int)
No error message! The compiler prints 2
successfully. However, if you make the value of string_to_int hello
and try to convert the variable to an integer, you will get the value nil
. hello
does not contain any numbers, so the variable cannot be converted to an integer.
Likewise, you can convert integers to strings. See this example:
var some_int : Int = 56
String(some_int)
Any time you want to represent a number, symbol, or letter and store it without the compiler interpreting it as an integer or string, specify the Character type. As mentioned, strings are useful for messages or text. For instance, if you are building an application, the text input into fields of the app are generally interpreted as strings.
Optional Variables
Swift 3.0 is unique in that it contains optional variables. Optional variables are variables that can contain the value of nil. They can be useful for running tests.
Clear your code from the previous section and set up a new variable:
var someVariable : Int = 400
You can even re-assign its value on a new line like so:
someVariable = 500
To make someVariable an optional variable, write a question mark after its type. If you do not give the variable a value, it will receive the default value for optional variables: nil.
var someVariable : Int?
This time, when you print someVariable, nil
will show up in the right sidebar. If you want to give someVariable the value nil manually on the next line of code, you can only do so if the variable's type is optional. If you tried to assign nil to a variable of type Integer, you would receive an error message.
someVariable = nil
As mentioned, optional variables are useful for running tests, such as running certain code only if a variable's value is nil.
Summary
This chapter covered the following types of variables:
Booleans – true or false
Integers – numbers that have no decimals
Floats and doubles – numbers with decimals
Characters and strings – ways to represent letters, numbers, or symbols in code without having them take on their real values
Optional values – can contain the value nil
CHAPTER 2: If Statements
If statements create control flow into code. They allow you to test a condition and execute code based on the outcome of that test. This chapter focuses on several derivations of the if statement, including:
if statements
multiple conditions in one if statement
else if statements
else statements
if let statements
Typically, these statements work like a true or false. Let's set up an if statement. Open a new Playground file. Type the keyword if, and select if - Swift If Statement. Xcode will automatically produce the following if statement, which contains placeholders for the condition and code to be executed.
if condition {
code
}
An if statement tests a condition, such as if a variable equals a value. The code in the if statement will only execute if the condition passes as true. In the present if statement, replace condition with someTest passes. You can choose whether to put someTest passes in brackets. It is optional in Swift, but other programming languages require it.
if someTest passes {
code
}
code is where you put the code that executes if the test passes. If the test does not pass, the code within the curly brackets will be skipped.
Basic If Statement
In this part, we will look at a basic if statement in action. We will look at how code flows from line to line through an if statement. Additionally, we will use a true/false test to test if select questions and answers are equal. If they are, we will run certain code.
Let's look at an if statement applied to a true/false test. Suppose you want to check your answers to a test and record your score. Create a new Boolean variable named question1 that has the value true.
var question1 : Bool = true
The compiler will print true
in the right sidebar. In our scenario, this means that the test-taker answered Question 1 with true
. Note that declaring the variable to be of type Bool is optional but is good practice.
Furthermore, our test needs a constant that represents the answer to Question 1:
let answer1 : Bool =
If answer1 is the correct answer, it should be a constant because the correct answer should not change. On the other hand, question1 is a variable because we may want to alter it later.
For this example, create another question and answer:
var question2 : Bool = false
let answer2 : Bool = true
At the end of a test, a