Day 3 - Playground

Aug 31, 2015 at 08:52 am, by Pierre Liard

I am now at the start of section four "Swift 2 Deep Dive (Using Playgrounds)". In his introductory lecture, Rob asks his students to think already to an app they are going to make: It may be one that you want to make for yourself, one that might generates some revenue, one developed for a family friend, a business or a charity, or just for a little bit of fun. It's always great to have a project in mind you can work toward. I love that. It's kind of provocative when you think you have only a few tricks in your bag, but so stimulating. You're not learning for itself, but for creating something on your own. I am not yet sure of what kind of app I would like to develop. Any suggestion would be welcomed.

Back to our today's chapter, we are about to dive deeper into Swift. Apple has created a very neat tool allowing beginners as experienced programmers to test their code without damaging the project they are working on: the playground. It is a very fun part of Swift. It allows to write code and to see immediately the result without compiling. With it, I am now ready to learn the fundamentals of Swift 2: variables, arrays and if statements. Compared to other programming languages I know, these fundamentals are pretty similar to the exception of one element: Swift is a strongly typed language. There is not a strict definition of what a strongly typed language is, but one of the rules is that data types have to be determined at compile time, and only operations appropriate to that type are allowed (see Difference between strongly and weakly typed languages).

Let's use Swift's playground to understand better this distinction:

var a:Int = 10
var b:Double = 23.34
var results = a * b

We have two variables, a and b. One is of type integer (whole number), and the other is of type double (decimal number). Their types have been made conspicuous by adding a colon and the type after the variable name. Contrary to C# for example, the type doesn't need to be indicated in Swift, but it may be easier, in a complex project, to precise it each time. In any case, trying to multiply two different types is not possible without converting one type to another as follows:

var a:Int = 10
var b:Double = 23.34
var results = Double(a) * b

In other words, Swift doesn't let you add together apples and pears. Some popular languages, like php or JavaScript, are less strict and allow the mix of different types that might, sometimes, produce very strange and unexpected results.

I have noticed that arrays seem to be a subject of choice when learning a programming language. They are in their simplest way a bucket containing a certain number of values generally of the same type. Swift, despite being a strongly typed language, accepts different types in an array :

var array = [20, 30, "Paul", 34, "Julia"]

Even though Rob said it is strongly advised not to mix types in arrays, I find this particularity a bit odd for a strongly typed language. I would be interested in knowing the logic behind allowing different types in a array.

What is more interesting is the way Swift creates dictionaries. They are arrays with indexes (or keys) and a series of values:

var menu = ["filet mignons": 35.45, "lasagna": 23.55, "mixed salad": 7.99]

The first element is the key, and the second after the colon is the value. Dictionaries are probably the most common use of arrays. They make possible different kind of operations, like adding, removing, counting, etc. In the above example, the cost of each plate can be added together like so:

var menu = ["filet mignons": 35.45, "lasagna": 23.55, "mixed salad": 7.99] 
var totalCost = menu["filet mignons"]! + menu["lasagna"]! + menu["mixed salad"]! 
print("The total cost is: \(totalCost)")

Notice the exclamation point after each key. As seen in the second day, it tells Swift that there is for sure a value for each key. Here is the result as printed in the playground:


Another "classic" of any programming language is of course the if statements. I would like for now to underline the difference between one single equal sign and a double equal sign: it is often overlooked or misunderstood.

var myName = "Pierre"
if(myName == "Pierre") {
print("Welcome " + myName)

The single equal sign attributes a value to a variable, whereas the double equal sign compares two variables to see if they are IDENTICAL. In the above example, the first equal just gives a value to the variable "myName", when the second compares if the value contained in the variable "myName" is identical to the value "Pierre", typed for example by a user in a login form. This is essential: if statements look first to see if two values are identical, before doing anything else. To express the notion of NOT (like username not equal to "Amy"), Swift and other languages use !=. The double ampersand && means AND, whereas the double vertical bar || signifies OR.

Let's illustrate this with a common example: when you input your username and your password to log in into some website, the software will first compare your input to what is in its database. There are four logical possibilities:

  1. your input matches the username and password in the database,
  2. your input doesn't match anything,
  3. the inputted username is correct, but the password is false,
  4. the inputted username is wrong, but the password is correct.

Here is a way to express this situation with an if statement. Before that, I would like to signal that Swift doesn't need the parenthesizes after if, but I personally prefer using them to clearly distinguish what belongs to the condition and the action.

var username = "Amy"
var password = "123myPassword"

if (username == "Amy" && password == "123myPassword"){
print("Welcome " + username)
} else if(username != "Amy" && password != "123myPassword"){
    print("Both your username and password are wrong")
} else if (username == "Amy"){
    print("Sorry, your password is wrong")
} else {
    print("Sorry, your username is wrong")

Variables, arrays and if statements are relatively simple to understand, but are at the core of the applications running in any iOS device. In the next lecture (29), we will build an app putting them in practice. The title "The Guessing Game" is intriguing enough to already wet my curiosity!

Leave a comment

Login to comment a post