Insights from Our Experts

Blog image

Optionals in Swift

Author Image

Rijaz Rasheed,Associate Software Engineer

Optionals is something new for a non-swift iOS developer. Although it is similar to ‘nullable’ in objective-c, the use of optionals in Swift is way beyond that. Optionals prevent run-time errors caused due to the absence of values. In swift, we cannot define a variable(or a constant) as ‘nil’. Every variable is expected to have some value. so we can declare a variable as optional, by adding a question mark after its type.

var nilString : String?    // nil
let optionalValue : Int?  // nil

Now the value of ‘nilString’ is taken to be nil, as far as there is no value in it. But, why do we this??? Remember Swift is known as a safe language. Take a situation in which a nil parameter is passed as an argument to a function, What if we do some operations on it without knowing that it doesn’t have any value?. it will compile just fine but will cause run time errors. Optionals are used to avoid this kind of situations.

Accessing Optionals

We can access the value of an optional in two ways.

By adding an exclamation mark(!) after the variable. This is called Forced unwrapping. i.e, we are forcefully accessing the underlying value of it. Forced unwrapping is not recommended unless you are 100% sure that the optional contains value in it. If it doesn't have any value, it will cause runtime errors

print(nilString!)    // error    
nilString = Not empty Anymore
print(nilString!) // Not empty Anymore

By adding a question mark(?) after the variable. This is called Optional chaining but is used only to access the properties, methods or subscripts of an optional. Here, if the optional contains any value, the value is returned, otherwise ‘nil’ is returned. This method is a better alternative to forced unwrapping because it won’t cause any error due to the absence of value.

class Multiplex {
let noOfScreens = 5
class Mall {
var multiplex : Multiplex?
let cityMall = Mall()
cityMall.multiplex?.noOfScreens   // nil

Choosing the safe way

Both of the above ways fail if there is no value in it, so it is always safe to check if the optional contains any value before using it. This can be done by Optional binding. i.e.

if let bindedString = nilString {
} else {
print(no value)

The code in the braces is executed if the optional has any value in it. If it is ‘nil’, the code in the else loop is executed.

Now if we are very much sure that the optional always contain some value, then we can make it an Implicitly unwrap optional. This is done by declaring it using an exclamation mark(!).

let mustValue : Int! = 10
let noOfItems = mustValue

We can access it using its name since there is no need to unwrap it every time.

One way to use the optional is that we can assign some other value to a variable if it is empty. This is done by nil coalescing operator(??).

var defaultString : String = Default value
var originalString : String = \(nilString ?? defaultString)

If the nilString is empty, the value of defaultString is assigned to originalString.

Optionals is a useful concept you can use when you are programming in Swift. Did you notice all the outlets of UI elements are implicitly unwrapped optionals. This shows the importance of it.  All the basic concepts of optionals are discussed here, you can refer to Apple Docs to know more about it.

I Need

Help for