This site is retired and is no longer updated since November 2021. Please visit our new website at https://www.teamscode.org for up-to-date information!
More about Optionals in Swift

else-if statements

With the skills you have learned right now, here’s how you will write a program that assigns a student’s grade. Let percent be the percentage a student has in a class and grade be the grade you give him or her. Grades will be assigned following this pattern:(90%+)=A,(80%+)=B,(70%+)=C,(0%+)=F(for the sake of simplicity). Here is what you might write:

   if percent > 90{
        grade=”A”
   }
   if percent > 80{
        grade=”B”
    }
   if percent > 70{
        grade=”C”
    }
   if percent > 0{
        grade=”F”
    }

You might do something different but this code, in general, illustrates the mistake you would make. If you go through the code with random values you might find that by the end of running the program, the student’s grade is always an “F”. That’s certainly not what we wanted. A fact I hid from you is that when you put multiple if statements one after the other, they magically don’t become related. Looking at all the if statements separately, this happens because in the place where we make a student get an F, we ask if their percentage is over 0%. If they have 92% in the class, of course they have over 0% in the class. The same applies if they deserved a B or a C. There are two way to deal with this problem: add multiple conditions to one if statement or relate the if statements. What I mean by “relate the if statements” is that we need to combine the if statements in a way that checks if a percentage is over 90(an A) and if it’s not(we know it’s not an A), check if it’s over 80(a B) and if it’s not(we know it’s not an A or a B), check if it’s over 70(a C) and if it’s not(we know that it is not an A or a B or a C), we come to the conclusion that it’s an F.

else if statements let us do that. Here is what I described in the previous paragraph in the form of Swift code:

   if percent > 90{
        grade=”A”
   }
   else if percent > 80{
        grade=”B”
    }
   else if percent > 70{
        grade=”C”
    }
   else{
        grade=”F”
    }

Now, all of those else if statements are related and work together. If any of conditions is true, the compiler doesn’t bother checking conditions that are written below it. The else keyword is differently used in the case when it is used with else if. When use that way, the code under it is run only when the condition in the last else if is not satisfied. The last else if is not true only if the else if above it is not true and so on. So we can say that, the block of code(lines of code enclosed in curly braces) under the else keyword is run only when none of the conditions in the list of else if and if statements is not satisfied.

The Ternary operator

The ternary operator is a way of shrinking a particular if-else statement to one line. The if-else that was shrunk is one that only assigns a value to the same variable in both the if block and the else block like shown below:

   var b = 100
   if b < 90{
        b=10
   }
   else{
        b=40
   }

If the value of b is less than 90, b becomes 10 else it becomes 40. The ternary operator can do the same with this line of code:

   b = (b < 90) ? 10 : 40

That is the only thing the ternary operator does. It assigns values based on a boolean condition.

Now let’s get back to optionals.

Optional Binding

Optional Binding is a kind of if statement that is used to check if an optional variable contains a value or just contains nil. If the optional variable contains a value, then the block of code in the if statement will run. Otherwise, the whole if statement is skipped over by the compiler.Here is the syntax for an optional binding statement:

   if let b = a{
        print(b)
   }

In the above code, variable a is the optional we want to check for emptiness. If a does have a value that is not nil, then the value of a is copied over to variable b. b exists only within the optional binding statement(so you don’t have to be super stressed about what you want to name it). Then, the value of b(which is the value of a) is printed on the console. Again, if a has a value of nil, the whole optional binding statement will be skipped over by the compiler.

Forced Unwrapping

Unlike regular variables, optionals have to be unwraped like a gift box so that you can look inside them. To use the value of an optional in your code, you NEED to unwrap it. Sometimes, we don’t know whether an optional has a value or not. But sometimes, we are absolutely sure that it does. Only when we are sure, we should unwrap it. If you unwrap it when it has a value of nil, you will get a Fatal error and your program will terminate midway. To unwrap an optional variable, all you have to do is add a ! to the end of the name of the optional whenever you want to use the value it holds.

   var num:Int? = 2000
   var sum = num! + 18

The result of that code is sum=2018!

Implicitly unwrapped optionals

If you know when you are initializing the optional that it is never going to have a value of nil, then you can declare the variable as an implicitly unwrapped optional. This is how you do it:

   var hello:String!="Hello"

All you had to do was replace the ?(used for regular optionals) with !.

Written by Valliappan Valliappan

Notice any mistakes? Please email us at learn@teamscode.com so that we can fix any inaccuracies.