Swift Optionals

In swift, optional is a type that is used to hold the value or absence of value means nil values. Nil represents the absence of value.

 

Generally in swift if we declare a variable and not assigned initial value or if we set nil value then we will get a compile-time error because by default those are non-optional.

 

Following is the simple example of defining variables without any initial value in swift programming language.

 

var firstname: String = "Tutlane"

var lastname: String  // It will throw a compile-time error

var uname: String  = nil // It will throw compile-time error

When we execute the above variable statements we will get a compile-time error because we didn’t assign any value to the “lastname” variable and we assigned “nil” to uname variable.

 

We got a compile-time error because in swift by default variables are non-optional. So if we define any variable without assigning any initial value or nil value we will get compile-time problems.

 

To solve this problem and indicate the absence of value the swift introduce type called “optional”. The optional will be defined by using a question mark (“?”) operator after the type declaration.

Swift Optional Declaration

Following is the syntax of declaring optional value with variables.

 

var <VariableName>: Datatype<?>

If you observed above syntax we defined question mark (“?”) operator after the data type declaration.

Swift Optional Example

Following is the simple example of using optional in a swift programming language to define the optional type for variables.

 

var firstname: String?

var phonenumber: Int?

var character: Character?

print(firstname)

print(phonenumber)

print(character)

If you observe the above example we declared three Optionals with different data types and we didn’t assign any initial value for the variables.

 

When we execute above program in swift playground it won’t return any compilation errors instead we will get the result like as shown below.

 

nil

nil

nil

Swift Force Unwrapping 

In swift if we define variable as optional means we need to unwrap the variable value using exclamation mark (!) otherwise we will get variable value with “Optional” keyword.

 

Following is the simple example of using Optional with variables to assign nil value in a swift programming language.

 

var firstname: String?

firstname = "Suresh"

if firstname != nil {

print("FirstName is \(firstname)")

}

else {

print("No FirstName ")

}

If you observe above example we defined variable “firstname” with nil value so we will get result like as shown below.

 

FirstName is Optional("Suresh")

If you observe the above result we got an Optional keyword along with firstname variable value. To solve this problem we need to unwrap the variable value using an exclamation mark (!).

 

Now we will add the exclamation sign (!) with the variables which we assign optional (“?”).

 

var firstname: String?

firstname = "Suresh"

if firstname != nil {

print("FirstName is \(firstname!)")

}

else {

print("No FirstName ")

}

If you observe above example we added exclamation mark (!) to the optional variables in example. 

 

Following is the result of the above swift optional program with an exclamation mark to unwrap the optional variable.

 

FirstName is Suresh

If you observe above result the Optional keyword removed from the string variable.

Swift Automatic Unwrapping

If you observe the above example we are unwrapping optional value manually using an exclamation mark (!). In case if you want to unwrap optional value automatically without doing any additional changes then we need to declare the variable with an exclamation mark (“!”) instead of question mark (“?”).

 

Following is the example of unwrapping optional value automatically using an exclamation mark (“!”).

 

var name: String!

name = "Suresh Dasari"

if name != nil{

print("\(name)")

}

else {

print("No Name ")

}

When we run above program we will get the result like as shown below.

 

Suresh Dasari

Swift Optional Binding

In swift, by using optional binding we can find that optional contains value or not. In case if optional value present in current context then it will store it in a temporary variable otherwise the nil value and it indicates that there is an absence of value.

 

Following is the simple example of Optional binding in swift programming language.

 

var firstname : String?

firstname = "Suresh"

 

if var name = firstname{

print("FirstName is \(name)")

}

else {

print("No FirstName ")

}

If you observe above example if value present in “firstname” then the value assigned to new variable called “name”.

 

When we run the above program in a swift playground that will return a result like as shown below.

 

FirstName is Suresh

Swift Optional with For Loop

In swift, by using for…in loop we can print all the values in an array which we declare with Optional sign. 

 

Following is the simple example of printing each element in an array by using for…in loop.

 

let optionalInt:[Int]? = [100, 200, 3000]

for i in optionalInt ?? [Int]() {

print(i)

}

If you observe above example we are accessing array values using for…in loop. Following is the result of above swift optional with for loop program.

 

100

200

3000

 This is how we can use optional in a swift programming language to maintain simple value or absence of value and unwrap optional variables based on our requirements.