Swift Program to Convert Char type variables to Int



This tutorial will discuss how to write swift program to convert char type variable to int.

Swift support various datatypes and character and integers are one of them. Character represent single-character string like, “2”, “a”, “l”, etc. Whereas Integer represent numeric values like 2, 3, 45, 6, etc.

To convert char type variable into Int type we can use any of the following method.

Method 1 - Using whole Number Value Property

We can convert char type variable into Int type using whole Number Value property. This property will convert character into number value if the character represent a whole number. It will return nil if the character does not represent whole number or the value is too long to be integer.

Syntax

Following is the syntax −

Character. wholeNumberValue

Example

The following program shows how to convert char type variable to int.

import Foundation
import Glibc
let mychar : Character = "5"

// Converting character into integer
if let myNum = mychar.wholeNumberValue
{
   print("Number is: ", myNum)
}
else{
   print("Not a valid Number")
}

Output

Number is: 5

Here we assign single digit like “2”, “4”, etc. in the character variable(that is mychar), if we assign multiple digits like “234”, “23”, etc. you will get errors because after adding one more digit it will become a string.

Method 2-Using Int() function

We can also convert character into integer using Int() and String() function. We do not have a direct method like Int and String for the conversion, so we first convert character into string, then into integer.

Syntax

// To convert into integer
Int(Value)

// To convert into string
String(Value)

Example

The following program shows how to convert char type variable to int.

import Foundation
import Glibc

// Number
let mychar : Character = "7"

// Converting character into integer
if let myNum = Int(String(mychar))
{
   print("Number is: ", myNum)
}
else {
   print("Not a valid Number")
}

Output

Number is: 7

Here we assign single digit like “2”, “4”, etc. in the character variable(that is mychar), if we assign multiple digits like “234”, “23”, etc. you will get errors because after adding one more digit it will become a string.

Conclusion

So in this tutorial we have used two different techniques to convert the Character type variable to int.


Advertisements