Optionals in Swift

Optional in Swift means the possibility of absence of a value for variable or constant.
In general a variable/constant is not allowed to have nil value, unless it is explicitly mentioned that the variable can go nil. For example

let a : Int = nil

will not compile.

Why Optionals are needed

Optionals are required in many cases in real world programming. For example if you are looking for a key in a dictionary it might be present or it might be absent. If you are downloading data from server, its not always guaranteed that you will get back the expected data. If you are trying to convert some data value to another type its not guaranteed that the value would get type casted into the target and returned. These are just few examples. This list of uses of optionals is long.

How to declare optionals

Declaring optionals is very simple. You just need to write the type with a trailing question mark. So if you want to declare an Int variable which can have nil value(declaring a as an optional Int). You can do it like this

var a : Int?

You can have optional of any type including your custom types.

Depending upon your context you might need to make sure that the value in optional is present. Accessing the actual value present in the optional is called unwrapping. There are various ways to unwrap an optional. But its not always required for you to unwrap the values to use it. For example if you are using your optional value as a parameter to a function that allows optionals, you can pass your value as an optional without unwrapping it.
There are several ways to unwrap an optional value. You can find all the ways to unwrap optionals here.

Though for using optional you don’t need to know how are they implemented in Swift. But its always better to know that, it helps in broadening your understanding. So let explore that

How are optionals implemented in Swift

You use the Optional type whenever you use optional values. The Optional type is an enumeration with two cases. Optional.none is equivalent to the nil literal. Optional.some(Wrapped) stores a wrapped value. For example:

     let number: Int? = Optional.some(56)
     let noNumber: Int? = Optional.none
     print(noNumber == nil)    // Prints "true"

The definition of Optional is like this in Swift

public enum Optional<Wrapped> : ExpressibleByNilLiteral {

    /// The absence of a value.
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none

    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)

Above is just partial definition of Optional(Just cases are shown and not the methods).

So after seeing the definition you know that we can declare an optional Int like

//long form to delcare an optional Int
let number: Optional<Int>

That is just the long form. You should avoid using it for readability purpose. You should always declare your optionals with trailing question mark(?) with type.

Something about nil in Swift

Swift’s nil is not the same as nil in many other languages. In most of the other languages, nil is a pointer to a nonexistent object. In Swift, nil is not a pointer, it is the absence of a value of a certain type. Optionals of any type can be set to nil , not just object types.
Remember that nil cannot be used with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.

One question before closing the topic.
Consider the following piece of code

var a : Int? = 5
var b =  a
b = nil ///IS IT OK?

What is your guess? Can b be assigned nil here?
YES!. As b is being assigned a variable which itself is optional Int so the inferred type for b would also be optional Int.

So that is what optional is in Swift.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s