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.
Last Updated : June 01, 2021

Swift - Int() function with Invalid value

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.

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

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 »

Advertisement
Advertisement

Related Programs

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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