Lesson 2 - Variables, type system and parsing in Swift
In the previous lesson, Introduction to Swift, the platform and Xcode, we learned how to work with Xcode, and created our Playground to run Swift code.
In today's Swift tutorial, we're going to look at the so-called type system.
We'll introduce basic data types, and we'll work with variables. We'll also talk
about the difference between the var
and let
keywords.
Variables
Before we start with data types, let's make sure we understand what a
variable is (if you're already familiar with programming, please excuse a short
explanation). Surely, you remember variables from Math class (e.g.
x
), in which we could store some value, usually a number. A
variable in IT is really the same thing. It's a place in computer memory where
we can store some data, e.g. a username, the current time or a database of
articles. This place has a certain reserved size, different variable types have
different sizes, which the variable can't exceed, e.g. an integer number can't
be greater than 2 147 483 647.
A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory, and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.
Type system
There are two basic type systems: static and dynamic.
- In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have types internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.
- On the other hand, we have the static type system. It
requires us to declare the variable type, and this type is unchangeable from
then on. Meaning that, if we try to store a user object into a
String
, we'll get yelled at by the compiler.
Swift is a statically typed language. All variables have a fixed data type. However, we don't always have to specify this data type, the compiler will choose the appropriate one if not specified explicitly. The great advantage is that before running the program, the compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check our source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and the interpreter will stop the program. Swift won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).
Let's make a sample program, so that you'll be able to apply this newly acquired knowledge. We'll continue with the theoretic part of it all next time. Here are three basic data types:
- Numbers:
Int
- Real numbers (
10.12
,...
):Double
- Texts:
String
Variable printing program
We'll go ahead and declare an integer variable, name it a
, store
the number 56
in it, and run it in Playground. You can create a new
Playground or use the one from the previous lesson.
var a : Int
a = 56
The first command declares a new variable, a
, of the
Int
data type. This variable will be used to store integers i.e.
whole numbers. The second command assigns a value to the variable using the
=
operator we all know from math classes. We could make the code
shorter by declaring and initializing the variable in a single step:
var a = 56
The compiler recognizes that 56
best matches the
Int
data type and assigns it in the background. Of
course, we could also specify the type explicitly:
var a : Int = 56
We usually don't specify the types like this in Swift.
The same program for a real number variable would look like this:
var a : Double var a = 56.6
It's almost the same as the code for integer. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.
Var
vs. let
So far, we've declared variables using the var
keyword. However,
in the world of Swift, you'll meet the let
keyword
more often. It's used to declare a constant variable that cannot be
further changed. Since we mostly don't need to change values in our
programs, we use let
primarily, and var
only in case
we plan to change the value of a variable. let
ensures that a variable always has a constant value we have
assigned to it the first time. This way there won't ever be a situation when
some part of our code would accidentally change our variables.
We can simply try the functionality of let
like this:
let a : Int a = 56 a = 22
As you can see, Playground reports an error since it's not possible to change
the value of a let
variable.
Parrot program
The previous program was a bit boring, let's try to respond to user input
somehow. Let's write a program named Parrot. You can probably guess what it will
do - it will repeat (twice) what the user has written. We haven't tried to read
anything from the console yet, but it's actually very simple. Playground now
won't be enough, we have to create a new Command Line Tool project, which we
have already learned to created before. There is the readLine()
method that returns a String
from the console. Let's try to write
the following code:
print("Hi I'm Lora, the virtual parrot, and i love to repeat!") print("Type something in: ") var input : String input = readLine()! var output : String output = input + ", " + input + "!" print(output)
This is a little more fun, right? The first two lines are self-explanatory (they just print text). On
the fourth line, we declare a String
input
.
input
will contain the return value of the readLine()
function, i.e. whatever the user entered to the console. Don't worry about the
exclamation mark for now, it's there so we don't have to validate the input. To
make the code more readable, we create another String
variable for
the output. The interesting part of the code is when we assign the value to
output
, we do a string concatenation. We use the +
operator to join several strings into one. As you can see, it doesn't matter
whether it's a variable or it's an explicitly declared string in quotation marks
in our source code. We assign the input
to the variable, then a
comma followed by a space, then input
again and finally an
exclamation mark. Then the program will display this variable and terminate.
Hi I'm Lora, the virtual parrot, and I love to repeat! Say something: Lora wants a cracker! Lora wants a cracker!, Lora wants a cracker!!
We can assign values to variables right in their declaration, so we could replace:
var input : String input = readLine()!
with:
val input = readLine()!
We could shorten the program in many other ways, but generally, it's better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.
Doubler program
The doubler program will retrieve an input number, double it and display the result. With the current knowledge we possess, we could write something like this:
print("Enter a number and I'll double it: ") var a : Int = readLine()! a = a * 2 print(a)
Notice multiplying the number a
in an assignment. Swift will
report an error and highlight the line on which we try to get the value from the
console and store it into the Int
variable. We've just seen type
checking in action, readLine()
returns a String
, and
we're trying to assign it to the Int
variable. Everything from the
console is text, even if we enter a number. We need to parse it
first.
Parsing
Parsing means converting from text to another specific type, e.g. numbers. In
many cases, you get data from the user or some service as String
but you need it to be, for example, Int
or
Double
for calculations and such. Parsing in Swift
is very easy, however, it has an important catch. We'll talk about it down
below. If we want to parse an Int
from a String
, we
write the following:
val a = Int("343")
We can see that the Int
data type offers a
constructor (a method creating particular variable, better said object, we'll
talk about them later) taking a String
and creating a number from
it. Let's use this in our program:
print("Enter a number and I'll double it: ") val input = readLine()! var a = Int(input) // eventually Double a = a * 2 print(a)
If we needed to parse a real number, we'd do the same for the
Double
type, i.e.
var a = Double(input)!
.
Of course, parsing doesn't have to be successful. Imagine that the text would
be "word"
instead of a number. We'll write exclamation marks
after parsing functions for now, as well as after every function that can be
processed unsuccessfully. We'll discuss this topic further in the following
lessons.
Simple calculator
Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.
print("Welcome to calculator") print("Enter the first number:") let a = Double(readLine()!)! print("Enter the second number:") let b = Double(readLine()!)! let sum = a + b let difference = a - b let product = a * b let quotient = a / b print("Sum: \(sum)") print("Difference: \(difference)") print("Product: \(product)") print("Quotient: \(quotient)") print("Thank you for using calculator.")
The output:
Welcome to calculator! Enter the first number: 3.14 Enter the second number: 2.72 Sum: 5.86 Difference: 0.42 Product: 8.5408 Quotient: 1.15441176470588 Thank you for using calculator, press any key to exit.
Notice 2 things. First, we simplified parsing from the console, so we don't
need a String
variable (we wouldn't use it further anyway).
Secondly, at the end of the program, we need to print the numbers, but because
the print()
method requires the String
type, we "wrap"
our numbers (or anything else) into \()
. This practice is called
String Interpolation, and the expression inside \()
is evaluated
internally. We could even perform operations such as e.g. multiplication there.
See below.
print("Sum ${a + b}")
In the following exercise, Solved tasks for Swift lessons 1-2, we're gonna practice our knowledge from previous lessons.
Download
By downloading the following file, you agree to the license termsDownloaded 389x (100.7 kB)