Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Character to Integer in Swift

Tags:

swift

I am creating an iPhone app and I need to convert a single digit number into an integer.

My code has a variable called char that has a type Character, but I need to be able to do math with it, therefore I think I need to convert it to a string, however I cannot find a way to do that.

like image 605
Nick Harris Avatar asked Apr 21 '16 22:04

Nick Harris


People also ask

How to convert a string into integer in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do I check if a string is int Swift?

Swift – Check if Variable/Object is Int To check if a variable or object is an Int, use is operator as shown in the following expression. where x is a variable/object. The above expression returns a boolean value: true if the variable is an Int, or false if not an Int.

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.


2 Answers

In the latest Swift versions (at least in Swift 5) there is a more straighforward way of converting Character instances. Character has property wholeNumberValue which tries to convert a character to Int and returns nil if the character does not represent and integer.

let char: Character = "5" if let intValue = char.wholeNumberValue {     print("Value is \(intValue)") } else {     print("Not an integer") } 
like image 84
parametr Avatar answered Sep 18 '22 23:09

parametr


With a Character you can create a String. And with a String you can create an Int.

let char: Character = "1" if let number = Int(String(char)) {     // use number     } 
like image 42
Luca Angeletti Avatar answered Sep 17 '22 23:09

Luca Angeletti