Swift program to demonstrate the Int() function with Invalid value

Here, we are going to demonstrate the Int() function with Invalid value in Swift programming language.
Submitted by Nidhi, on June 01, 2021

Problem Solution:

Here, we will try to convert a non-numeric string into an integer number using Int() function. Then we will print the appropriate message on the console screen.

The Int() function returns an optional integer, then we need to unwrap the integer number.

Program/Source Code:

The source code to demonstrate Int() function with an invalid value is given below. The given program is compiled and executed successfully.

// Swift program to demonstrate the
// Int() function with Invalid value

import Swift;

var strCode:String = "ABCDEF";
if let num = Int(strCode)
{
    print("Number is: ",num);
}
else
{
    print("String does not contain valid number.");
}

Output:

String does not contain valid number.

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created a string strCode with the initial value "ABCDEF”. And, strCode does not contain a valid numeric value. Then Int() function return "nil" value. After that, we printed the appropriate message on the console screen.

Swift Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.