In the last tutorial, you learnt about Swift 4 Basics: Numbers, Operators and Strings. In this tutorial, you'll learn about variables, arrays and dictionaries. Let's get started!
Variables
An important concept in programming is variables. Variables are used to store values.
A good analogy for the variable is a box. You can imagine the name of the variable as the label on the box, and the value of the variable as what's stored inside it.
Let's create a new variable called name and then print it:
type=codeblock|id=swift_print_str_var|autocreate=swift4var name = "CommonLounge"print(name)
Output:
CommonLounge
The above is equivalent to saying: Store the value "CommonLounge" in variable name.
Yippee! Your first variable! 🙂
Of course, variables can be anything – numbers too! Try this:
type=codeblock|id=swift_print_int_var|autocreate=swift4var n = 4print(n)print(5 * n)
Output:
420
Remember we said all expressions in Swift evaluate to a single value? The result of evaluating a variable is simply the value stored inside it. So, the step-by-step breakdown of evaluating the above expression would be:
5 * n=> 5 * 4 <—- Swift looks up the value stored in variable "name"=> 20
You can always change the value stored inside the variable:
type=codeblock|id=swift_print_str_var_change_1|autocreate=swift4var name = "CommonLounge"name = "David"print(name)
Output:
David
When you store a new value in a variable, the old value gets tossed out. This means we can't get back to "CommonLounge" again, unless we stored it in some other variable. For example:
type=codeblock|id=swift_print_str_var_change_2|autocreate=swift4var x = "CommonLounge"print(x)var y = xprint(y)x = "David"print(x)
Output:
CommonLoungeCommonLoungeDavid
Above, when we did y = x, y now has the value "CommonLounge" inside it. Then we updated the value of x to "David", but y is unchanged.
You can also use a variable to assign value to itself.
type=codeblock|id=swift_print_str_var_change_add|autocreate=swift4var name = "CommonLounge"print(name)name = "Hello " + name + "!"print(name)
Output:
CommonLoungeHello CommonLounge!
When you do name = "Hello " + name + "!", you are telling Swift evaluate the expression "Hello " + name + "!", and store the result in name.
Here's another example:
type=codeblock|id=swift_print_var_change_add_mult|autocreate=swift4var a = 5print(a)a = a * 3print(a)a = a * aprint(a)
Output:
515225
Awesome, right?
The same way you used methods on values, you can use them on variables too:
type=codeblock|id=swift_print_var_uppercased|autocreate=swift4var name = "David"print(name)print(name.uppercased())
Output:
DavidDAVID
Here's the step-by-step breakdown of evaluating the above expression:
name.uppercased()=> "David".uppercased() <—- Swift looks up the value stored in variable "name"=> "DAVID"
What do you think happens if we try to assign an Int value to a variable which was originally a String? Try executing this code:
type=codeblock|id=swift_print_var_error|autocreate=swift4var name = "David"name = 10
What do you see? An Error telling us that we can't assign a number to the type string, but did we explicitly tell Xcode that name is going to be of the type String? We didn't. Let's see what's going on here.
Type inference
This is one of the key features of Xcode - Type-Inference. Xcode automatically decides the data type for the variable when the value is initially assigned to it.
var x = 7// Data type of x is Intvar y = 7.0// Data type of y is Doublevar z = "7.0"// Data type of z is String
We can explicitly also assign the data type to the variable. The syntax is as follows:
var <variable_name>: <datatype> = <value>
For example:
type=codeblock|id=swift_print_type_assignment|autocreate=swift4var x: Int = 7print(x)
Output:
7
More errors
What if we used the wrong variable name? Can you guess what would happen? Let's try!
type=codeblock|id=swift_print_var_typo_error|autocreate=swift4var city = "Tokyo"print(ctiy)
An error! As you can see, Swift has different types of errors. Swift will give you this error if you try to use a variable that hasn't been defined yet. If you encounter this error later, check your code to see if you've mistyped any names.
Variable names
But do you think you can name a variable however you wish to? Well no, we have to follow certain rules for naming a variable:
- The name of the variable cannot contain whitespace or mathematical operators or other characters except the underscore ( _ )
- The name should only contain alphabets, numbers and underscore
- The name cannot start with a number, although you can use a number in the later part of the name
Play with this for a while and see what you can do!