Swift Optionals

Ankish
Swift for iOS — the new face
5 min readSep 13, 2015

Optionals are a powerful feature of the Swift programming language, they carry a simple concept but can be complex to understand . Let’s review the basics.

Real time scenario of usage

Lets say we need to authorise students entry to a school. We define a simple class

class student {

var idCardNumber : String // Student should have an Id card to enter school

var tabletModel : String? // Student may or may not bring an tablet to enter school

}

Variables and Inference

Swift is a strongly typed language — all variable must have a defined type , unlike other scripting languages.

But Swift is also a strong type-inference language. It can infer the type from the context.

var mutableTablet = “iPAD” // remember here var is of type String. Swift infers it .

By Example

Lets use a simple example . There are buttons in a view with characters as their titles . If you press the button it prints them on a label and logs it.

Note : press option and click on a variable to reveal its type

Non Optional Type :

type of button

Optional Type ?

In swift there is a TYPE for all variables called OPTIONAL (?)

‘?’ indicates Optional — It has two optional values

1) NOT SET- Either it was never set or someone has set it to be NOT SET -its ( ‘nil’) or empty

2) SET to something

more of ????????

var currentTitle: String?

Note : String is NOT the type of the variable here . Type is OPTIONAL.

if this optional has valid value then its of type String.

String ?

You can call it an optional String . But its not a string. Its an optional that can be a string. Read it once more :)

if you print this you would get

output : String = Optional(“c”)

how do we get the correct value ?You unwrap it with ! .When you add !. Optional string is converted to String. Thats what is your actual value you are looking for.

Output String = c

All good till now.

But what if the title of the button is never set ? its a CRASH !

Most of the objects in Swift are optionals as they can are not set in the beginning .Swift forces you to make sure those unset scenarios are not shipped along and minimises the ‘notset’ crashes using Optionals.

Implicit Optional

Optional : var dummyString: String?

Implicit Optional : var dummyString: String!

You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafterAn implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed. The following example shows the difference in behavior between an optional string and an implicitly unwrapped optional string when accessing their wrapped value as an explicit String:

let optionalString: String? = “An optional string.”

let unwrappedString: String = possibleString! // requires an exclamation mark

let implicitUnwrappedString: String! = “An implicitly unwrapped optional string.”

let implicitString: String = assumedString // no need for an exclamation mark

Few one liners:

var dummyString: String? //Value is nil by default

let charString = sender.currentTitle! // The type of current title is String?

display.text=nil // allowed since its an optional

//optionals indicate that a constant or variable is allowed to have “no value” or nil value

display.text= “Hello” // allowed since its an valid value

display.text=display.text + charString // not allowed since display.text type is optional(?) + digit is String

display.text=display.text! + charString // allowed since display.text type is now String from optional(?) using (! unwrapping) + digit is String

How do we safely handle this?

For normal optionals :

remember optionalString is a optional it can have only two types nil or valid value. You check if its not nil then it has to be a valid value which you can use by unwrapping it !

For Implicit Optionals

implicit optional here is display

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

You will find optional everywhere is swift. That makes a swift a type safe language.You usually give an input to a function and expect a positive output and you dont handle it.Output can sometimes give unexpected results or nil values .Swift forces you to handle it to save you from runtime crashes.

Will keep updating more on optionals. Happy swifting !

By Ankish Jain , iOS Developer.

--

--