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!
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:
var name = "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:
var n = 4// 45 * n// 20
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:
name = "David"// "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:
var x = "Commonlounge"// "Commonlounge"var y = x// "Commonlounge"x = "David"// "David"
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.
name = "Commonlounge"// "Commonlounge"name = "Hello " + name + "!"// "Hello 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:
var a = 5// 5a = a * 3// 15a = a * a// 225
The same way you used methods on values, you can use them on variables too:
name = "David"// "David"name.uppercased()// "DAVID"
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:
var 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? No right!
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 - Intvar y = 7.0// Data type - Doublevar z = "7.0"// Data type - String
We can explicitly also assign the data type to the variable. The syntax is as follows:
var <variable_name>: <datatype> = <value>
var x: Int = 7
What if we used the wrong variable name? Can you guess what would happen? Let's try!
var city = "Tokyo"ctiy// Use of unresolved identifier '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.
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!
The variables you saw so far only stored a single number or string. What if we wanted to store numbers or strings? This is exactly what an Array does.
Arrays are collections of values of a single type stored together. We can not have an array containing numbers and strings together. Arrays are always enclosed in 
var stringArray = ["Commonlounge", "Swift", "iOS"]// ["Commonlounge", "Swift", "iOS"]var intArray = [3, 42, 12, 19, 30, 59]// [3, 42, 12, 19, 30, 59]
You can also provide the array type explicitly:
var emptyIntArray = [Int]()
Note that you must provide the type explicitly if the array you are initializing is empty (like above). If there is at-least one element, then Swift can do type-inference.
Specific items in the Array are can be accessed using indexes. An index is the number that says where in a list an item occurs. Array indexes start from 0 and go on till one less than total no of items. For example, in our intArray we have 6 items so our indices will range from 0-5. At the 0th index we have "3", 1st we have "42", and on the 2nd we have "12" and so on.
Exercise: What will be the output of stringArray?
Important - Swift crashes if you give an out of range index. So stringArray, stringArray[-1] or stringArray all cause it to crash.
To change the value of the element present at a specific index in the array
//Changing the value of the element at index 3, i.e the 4th element in the arrayvar a = [1,2,3,4,5,6,7,8,9]a = 12a // [1, 2, 3, 12, 5, 6, 7, 8, 9]
You can also initialize Arrays using existing variables:
var name = "Commonlounge"var s = "Swift"var i = "iOS"var stringArray = [name, s, i]// ["Commonlounge", "Swift", "iOS"]
As with numbers and strings, we can do various operations on an Array. For example, you can even add (concatenate) two arrays just like strings:
var a = [1, 2, 3]var b = [4, 5, 6]var c = a + b// [1, 2, 3, 4, 5, 6]
Note: Make sure both arrays are of the same type
You can find out the number of elements present in the array by using the attribute .count
If you want to add new elements to your array, you have to use the .append() method or the .insert() method:
c.append(7)c// [1, 2, 3, 4, 5, 6, 7]c.insert(100, at: 2)c// [1, 2, 100, 3, 4, 5, 6, 7]
As you can see, append adds the value to the end, and insert inserts it at a particular position. Similarly, we have .popLast() and .remove():
c.popLast()c// [1, 2, 100, 3, 4, 5, 6]c.remove(at: 1)// 2 (the element that is removed is printed on the result bar)c// [1, 100, 3, 4, 5, 6]
As Arrays get large, .insert() and .remove() become slow (behind the scenes, each value has to be moved). But .append() and .popLast() are fast.
A dictionary is similar to the everyday dictionary you use, where you access values by looking up a key (the word is the key and its meaning is the value). In an Array we need to know the exact position of the value we want but in dictionaries we can look up a value with the help of its key. A key can be any string or number.
The syntax to define an empty dictionary is:
var words: [String: String] = [:]var errors: [Int: String] = [:]
The words dictionary we created, tells Xcode that our key and value pairs are both going to be of type String.
In general, the syntax is:
var <variable_name>: [<key_type>: <value_type>] = [:]
The errors dictionary contains Integer type as its keys and String type as its values.
What if we wanted our dictionary where the values could be Int as well as String type? Swift allows us to have multiple data types for our values but only one data type for our keys! For this, we use the Any keyword.
var person: [String: Any] = [:]
Let's create a dictionary with some values in it.
var person: [String: Any] = ["first name": "Parth","last name": "Shah","phone number": 9898310172]
Note: If all values were of the same type we wouldn't need [String: Any] as swift would automatically do type-inference.
With this statement, you just created a variable named person with three key–value pairs:
- The key "first name" points to the value "Parth" (a String object),
- "last name" points to "Shah" (another String),
- and "phone number" points to 9898310172 (an Int object)
Same as Arrays, dictionary elements can be accessed using indexes (keys).
person["first name"]// "Parth"
What happens if we ask Swift the value of a key that doesn't exist? Can you guess? Let's try it and see!
Look, we get nil for the keys that don't exist.
Dictionaries, like lists, are mutable, meaning that they can be changed after they are created. You can add new key–value pairs to a dictionary after it is created, like this:
person["favorite_language"] = "Swift"person// ["phone number": 9898310172, "last name": "Shah",// "first name": "Parth", "favorite_language": "Swift"]
Using the .count method on the dictionaries returns the number of key–value pairs in the dictionary. Go ahead and type in this command:
person.count// 4 (we initialised 3 key-value pairs and added one more above)
If you wish to remove a specific key-value pair from the dictionary, you have to assign the value of that key as nil
person["phone number"] = nil// The phone number is deletedperson// ["last name": "Shah", "first name": "Parth", "favorite_language": "Swift"]
To check if the dictionary is empty or not we use the .isEmpty attribute. This gives us a result in boolean values, i.e true or false.
Awesome! You know a lot about programming now. In this last part you learned about:
- variables – variables are used to store values
- Array – objects stored as a list of items
- dictionaries – objects stored as key–value pairs
Excited for the next part? 🙂