Swift Program to check if a variable is not nil

SwiftServer Side ProgrammingProgramming

This tutorial will discuss how to write a Swift program to check whether a variable is not nil.

A variable is used to store data in the computer’s memory so that users can further use them in their codes. It is like a container that holds data that can be used or changed later in the program. In Swift, we can check if a variable is not nil with the help of an inequality operator(!=).

Syntax

Following is the syntax −

Myvar != nil

Here, the value of Num can be of integer, float, or double type.

Below is a demonstration of the same −

Input

Suppose our given input is −

NewVar = 3.45566

Output

The desired output would be −

myVar variable is not nil

Algorithm

Following is the algorithm −

Step 1 − Declare variable of optional type.

var NewVar : Float?

Here optional type means where the value of a variable may be absent. Or we can say it supports two possibilities: either a variable has a value or a variable does not have a value.

Step 2 − Assign the value to the variable.

Step 3 − Using if else condition, we check if the given variable is nil or not using an inequality operator.

if (myVar != nil){
   print("myVar variable is not nil")
} else{
   print("myVar variable is nil")
}

If the given variable is not nil then it will return “myVar variable is not nil”. Otherwise it will return “myVar variable is nil”.

Step 4 − Print the output.

Example 1

The following program shows how t to check if a variable is not nil.

import Foundation import Glibc var myVar : String? myVar = "Hey" // Checking if the given variable is nil or not // Using inequality operator(!=) if (myVar != nil){ print("myVar variable is not nil") } else{ print("myVar variable is nil") }

Output

myVar variable is not nil

Here, in the above code, we check whether the defined variable is nil or not using an inequality operator using the following code −

if (myVar != nil){
   print("myVar variable is not nil")
} else{
   print("myVar variable is nil")
}

Here, myVar = “Hey” so the condition myVar != nil is true so we get "myVar variable is not nil” as an output.

Example 2

The following program shows how to check if a variable is not nil.

import Foundation import Glibc var NewVar : Float? // Checking if the given variable is nil or not // Using inequality operator(!=) if (NewVar != nil){ print("NewVar variable is not nil") } else{ print("NewVar variable is nil") }

Output

NewVar variable is nil

Here, in the above code, we check whether the defined variable is nil or not using an inequality operator using the following code −

if (NewVar != nil){
   print("NewVar variable is not nil")
} else{
   print("NewVar variable is nil")
}

Here, var NewVar : Float? Is of optional type and does not assign with a value so the condition NewVar != nil is false. Hence we get "NewVar variable is nil” as an output.

raja
Updated on 10-Oct-2022 14:34:08

Advertisements