Swift Optionals

  Total Views : 355
  Comments : 0
  Keywords : Swift optional type to hold value or no value with examples, Swift optional to force or automatic unwrapping with examples, Swift optional to provide compile-time check in application

Here we will learn optional in swift with example and how to use swift optional to force unwrap or automatic unwrap string in swift, optional binding in swift and use optional with for loop in swift with examples.

Swift Optionals

In swift optional is a type which is used to hold the value or absence of value means nil values. Nil represent 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 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 compile time error

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

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

 

We got 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 problem.

 

To solve this problem and indicate absence of value the swift introduce type called “optional”. The optional will be defined by using 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 swift programming language to define optional type for variables.

 

var firstname: String?

var phonenumber: Int?

var character: Character?

print(firstname)

print(phonenumber)

print(character)

If you observe above example we declared three Optionals with different data types and we didn’t assigned 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 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 above result we got Optional keyword along with firstname variable value. To solve this problem we need to unwrap the variable value using 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 above swift optional program with 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 above example we are unwrapping optional value manually using exclamation mark (!). In case if you want to unwrap optional value automatically without doing any additional changes then we need declare variable with exclamation mark (“!”) instead of question mark (“?”).

 

Following is the example of unwrapping optional value automatically using 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.

 

Suesh 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 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 above program in swift playground that will return 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 swift programming language to maintain simple value or absence of value and unwrap optional variables based on our requirements. 

 

PREVIOUS

Swift Characters
 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User