Swift Double - isEqual Function



The isEqual() method of the Double structure is used to check whether the given number is equal to the specified number or not. It will return a boolean value to represent the result. For example, we have two numbers: 23.5 and 45.6, now we use 23.5.isEqual(to: 45.6). This function returns false because 23.5 is not equal to 45.6.

Syntax

Following is the syntax of the isEqual() method:

func isEqual(to value: Double) -> Bool

Parameter

This method takes only one parameter, which is value. The value represents the number to which we compare the input number.

Return Value

This method returns a boolean value. If both the given numbers are equal, then this method will return true. Otherwise, this method will return false.

Example 1

Swift program to demonstrate how to use the isEqual() method.

import Foundation

// Input numbers
var number1 : Double = 8.0
var number2 : Double = 4.0
var number3 : Double = 45.0

//  Checking whether the given numbers are equal or not 
// using isEqual(to:) method
print("Result1:", number1.isEqual(to: 8.0))
print("Result2:", number2.isEqual(to: 34.5))
print("Result3:", number3.isEqual(to: 45.0))

Output

Result1: true
Result2: false
Result3: true

Example 2

Swift program to check whether the given numbers are equal to each other or not.

import Foundation

// Checking whether the given numbers are equal or not 
// using isEqual(to:) method
print("Result:", 18.0.isEqual(to: 2.0))
print("Result:", 23.5.isEqual(to: 23.5))
print("Result:", 34.5.isEqual(to: 34.5))

Output

Result: false
Result: true
Result: true

Example 3

Swift program to check whether the given numbers are equal to each other or not using isEqual() method.

import Foundation

// Input numbers
let num1 : Double = 34.66
let num2 : Double = 34.66

//  Checking whether the given numbers are equal or not 
// using isEqual(to:) method
if (num1.isEqual(to: num2)){
   print("Both the numbers are equal")
}
else{
   print("Both the numbers are not equal")
}

Output

Both the numbers are equal
Advertisements