What are optionals in Swift ( ? && ! ).

By | June 30, 2016

Swift introduces Optionals type, which handles the absence of a value.

Optionals say if there are set a value, then take that value, it can be of any type
AND else it is nil.

Basically It has two possible values,

None and Some(T),

where T is an associated value of the correct data type available in Swift.


Optional Integer declaration

var perhapsInt: Int?

Optional String declaration −

var perhapsStr: String?

The above declaration is equivalent to explicitly initializing it to nil like below

	var perhapsStr: String?  = nil

Comparing with Objective C

You have to assign a non-nil value to the variable. If you try to set a nil value to a non-optional, the compiler will say, “hey you can’t set a nil value!”.

	var message: String = "Swift!" // OK
	message = nil // compile-time error

But you can still do the same with Objective C

	NSString *message = @"Objective-C!";
	message = nil;

You’ll get a compile-time error for message as it’s not assigned with an initial value in swift. For those coming from Objective-C, you may be a bit surprised. In Objective-C, you won’t get any compile-time error when assigning nil to a variable or declaring a property without initial value:

	NSString *message = @"Objective-C!";
	message = nil;

However, it doesn’t mean you can’t declare a property without assigning an initial value in Swift. Swift introduces optional type to indicate the absence of a value. It is defined by adding a question mark ? operator after the type declaration. Here is an example:

	var message1: String?

You can still assign a value when the variable is defined as optional. However if the variable is not assigned with any value like the above code, its value automatically defaults to nil.

Unwrapping Optionals

We will check if a variable contains a value or not…

var message1:String? = findMessage()
let text = "Demo Message - "
let message = text + message1!  // runtime error

The above code will compile successfully, but this will cause a runtime error.

So to prevent this error…we will do a fix. we will unwrap the optional.

var message1:String? = findMessage()
let text = "Demo Message - "
if message1 {
    let message = text + message1!

We unwrap an optional by placing an exclamation mark (!) to the end of the optional’s name. In Swift this is known as forced unwrapping.

But remember that the optional should contain a non-nil value to do a operation on it.
So we check for nil condition before that using “if message1”.

Optional Binding

Optional Binding is another way to unwrap an optional.

we copy the value to a constant and check the optional.

var message1:String? = findMessage()
let text = "Demo Message - "
if let m = message1 {
    let message = text + m

Automatic Unwrapping

You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

For example

var message:String!

myString = "Hello, Swift!"

if message != nil {
}else {
   println("message has nil value")

Please send your valuable comments to coderzheaven@gmail.com

Leave a Reply

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