Variables, constants, strings, and semicolons
Our next step is to familiarize ourselves with the differences between variables, constants, strings, and semicolons in a bit more detail. We will work with and use Xcode playgrounds to put each of these into practice.
A variable is a value that can change. Every variable contains a name, called the variable name, and must contain a data type. The data type indicates what sort of value the variable represents, such as whether it is an integer, a floating point number, or a string.
Let's take a look at how we can put this into practice and create a variable in Swift.
First, let's start by revealing the console output window by navigating to View | Debug Area | Show Debug Area.
Next, clear the contents of the playground template and replace them with the following code snippet:
As you begin to type in the code, you should immediately see the Welcome to Learning the basics of Swift text magically appear in the right-hand pane in which the assignment takes place and it appears once more for the print
statement.
The right-hand pane is great for showing you smaller output, but for longer debugging output, you would normally take a look at the Xcode console.
A constant is basically a value that cannot be changed. Creating these constant variables prevents you from performing accidental assignments and can even improve performance.
Let's take a look at how we can put this into practice and create a constant variable in Swift.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the screenshot now:
As you begin to type in the code, you will immediately receive an error message stating that you cannot assign myGreeting
to our let
value because the object is not mutable. In Swift, you can control the mutability of the built-in Swift types by using either the let
or var
keywords during declaration.
A string is basically an ordered collection of characters, for example, "hello, world". In Swift, strings are represented by the String
data type, which represents a collection of values of the char
data type.
You can use strings to insert constants, variables, literals, and expressions into longer strings in a process known as
string interpolation, which we will cover later on this in chapter. This makes it easy to create custom string values for display, storage, and printing.
Let's take a look at how we can put this into practice, create a String
variable in Swift, and utilize some of the string methods.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the screenshot now:
As you can see in the preceding code snippet, we began by importing the Foundation
framework class, which contains several APIs to deal with objects such as strings and dates. Next, we declared our myGreeting
constant variable and then assigned a default string. We then used the uppercaseString
method of the string object to perform a function to make all of the characters within our string uppercase. In our next step, we will declare a new variable called newGreeting
and call the stringByAppendingString
method to append additional characters at the end of our string.
As you would have probably noticed so far, the code you wrote doesn't contain any semicolons. This is because in Swift, these are only required if you want to write multiple statements on a single line.
Let's take a look at a code example to see how we can put this into practice.
Delete the contents of the playground template and replace them with the following code snippet:
Take a look the following screenshot now:
As you can see in the preceding code snippet, we began by declaring our myGreeting
variable and then assigned a default string. In our next step, we declared a new variable called newString
, concatenated the details from our myGreeting
string, and used the uppercaseString
method, which cycles through each character within our string, making our characters uppercase.
Next, we appended the additional working with semicolons
string to the end of our string and finally used the print
statement to output the contents of our newString
variable to the console window. As you must have noticed, we included a semicolon at the end of the statement; this is because in Swift, you are required to include semicolons if you want to write multiple statements on a single line.
Numeric types and conversion
In this section, we will take a look at how we can perform arithmetic operations on our Swift variables. In this example, we will look at how to calculate the area of a triangle, given a base and height value.
Let's take a look at a code example to see how we can put this into practice.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the following screenshot now:
As you can see in the preceding code snippet, we started by creating our calcTriangleArea
function method, which accepts a base and a height parameter value in order to calculate the area of the triangle. In our next step, we declared two variables, base
and height
, which contain the assigned values that will be used to calculate the base and the height of our triangle. Next, we made a call to our calcTriangleArea
method, passing in the values for our base and height before finally using the print
statement to output the calculated area of our triangle to the console window.
An important feature of the Swift programming language is that all numeric data type conversions must be explicit, regardless of whether you want to convert to a data type containing more or less precision.
Booleans, tuples, and string interpolation
In this section, we will look at the various features that come with the Swift programming language. We will look at the improvements that Swift has over Objective-C when it comes to using Booleans and string interpolation before finally discussing how we can use tuples to access elements from a string.
Boolean
variables in Swift are basically defined using the Bool
data type. This data type can only hold values containing either true
or false
.
Let's take a look at a code example to see how we can put this into practice.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the following screenshot now:
As you can see from the preceding code snippet, we started by declaring our constant variable called displaySettings
and assigned it a default Boolean value of true
. Next, we performed a check to see whether the value of our displaySettings
variable is set to true
and called our print
statement to output the Display Settings is: ON value to the console window.
In Objective-C, you would assign values of 1 and 0 to denote true and false; this is no longer the case with Swift because Swift doesn't treat 1 as true and 0 as false. You need to explicitly use the actual Boolean values to stay within Swift's data type system.
Let's replace the existing playground code with the following code snippet to take a look at what would happen if we changed our value from true
to 1
:
Take a look at the following screenshot now:
As you can see from the previous screenshot, Swift detected that we were assigning an integer value to our Boolean data type and threw an error message.
Tuples provide you with the ability to group multiple values into a single compound value. The values contained within a tuple can be any data type, and therefore are not required to be of the same type.
Let's take a look at a code example, to see how we can put this into practice.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the following screenshot now:
As you can see from the preceding code snippet, we started by declaring a tuple variable called addressDetails
that contains a combination of strings. Next, we accessed each of the tuple elements by referencing their index values and displayed each of these elements in the console window.
Let's say that you want to modify the contents of the first element within your tuple. Add the following code snippet after your var addressDetails
variable:
Take a look at the following screenshot now:
As you can see from the preceding screenshot, we modified our first component within our tuple to the Apple Computers, Inc
value. If you do not want modifications to be made to your variable, you can just change the var
keyword to let
, and the assignment would result in a compilation error.
You can also express your tuples by referencing them using their named elements. This makes it really useful as you can ensure that your users know exactly what the element refers to. If you express your tuples using their named elements, you will still be able to access your elements using their index notation, as can be seen in the following highlighted code snippet:
Take a look at the following screenshot now:
As you can see from what we covered so far about tuples, these are really cool and are basically just like any other data type in Swift; they can be really powerful to use within your own programs. As we progress through this book, you will see tuples being used more frequently.
String interpolation means embedding constants, variables, as well as expressions within your string literals. In this section, we will take a look at an example of how you can use this.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the following screenshot now:
As you can see from the preceding code snippet, we started by declaring a tuple variable called addressDetails
that contains a combination of strings. Next, we performed a string concatenation to generate our output in the format that we want by accessing each of the tuple elements using their index values and displaying each of these elements in the console window.
Let's take this a step further and use string interpolation to place our address detail information into string variables. The result will still be the same, but I just want to show you the power of using tuples with the Swift programming language.
Clear the contents of the playground template and replace them with the following highlighted code snippet:
Take a look at the following screenshot now:
As you can note from the preceding code snippet, we removed the named types from our addressDetails
string contents, created a new type using the let
keyword, and assigned placeholders for each of our tuple elements. This is very handy as it not only makes your code a lot more readable but you can also continue to create additional placeholders for the additional fields that you create.
In this section, we will take a look at how to use the for…in
loop to iterate over a set of statements within the body of the loop until a specific condition is met.
The for…in
loops basically perform a set of statements over a certain number of times until a specific condition is met, which is typically handled by incrementing a counter each time until the loop ends.
Let's take a look at a code example to see how we can put this into practice.
Clear the contents of the playground template and replace them with the following code snippet:
Take a look at the following screenshot now:
The preceding code demonstrates the for…in
loop and the closed range operator (...
). These are often used together, but they are entirely independent.
As you can see from the preceding code snippet, we declared the exact same variables: fibonacci
, iTemp
, and jTemp
. Next, we used the for…in
loop to iterate over our range, which is from 0 to 19, while displaying the current Fibonacci value in the console window.