iOS Lesson 11: Optionals in Swift

So with this knowledge bit, we are going to cover a very fundamental part of swift that is Optionals in Swift. You are going to use this most of the times.

Optionals in Swift:

Optionals are kinds of things that differentiate between good and bad code that help prevent crashes.

Open up your Xcode and create a new playground. We are going to call this one “letsTryOptionals” and delete the Hello world line as we don’t need it.


The idea behind Optionals in Swift is that if you use them your code will be very much better then the code that can crash.

The syntax for optional is same as a variable “It just define something as optional by putting a question mark after the datatype”


var studentPresent : Int?


Above line defines a variable as an optional, it means that it may or may not have a value. So at some point in your program if you don’t know whether there is going to be a value in there or not then you mark it as an optional.

Let’s say you have an app that will check whether you have got the first price or not. It may or may not have a value so the best way is to mark it as optional.

In theory, we just mark a variable as an optional to make sure that if it doesn’t return any value then don’t crash the app at runtime.

When to use Optionals in Swift?

Anytime when you are not sure whether the variable will be going to have a value or not? Mark it as Optional!.

Make sure it has a value:

We can make sure that the variable has a value by using an if-let syntax.


if let winnings = studentPresent{




what we have done is that we have created a variable at runtime and passing the value of optional into it. With this, the code will only be going to run when there is a value in winnings constant.

We can take an example of an object, which is marked as an optional. If we would try to access any of its property the property will be marked as optional as well.

For now, we haven’t covered classes and Object-oriented principles in swift that is why you would be a little bit confused with this practical example. But, think of optionals as an option that will make your variable safe and prevent your app from crashing.

Optionals in Swift Example

So in this knowledge bit, we have covered Dictionaries. We have seen few examples how dictionaries work and how we can iterate through dictionaries. You can get all the code from here.

You can have a look at our whole IOS series as well.


Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Most Popular

To Top