Reputation: 479
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.
Upvotes: 47
Views: 53550
Reputation: 1102
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")
}
Upvotes: 70
Reputation: 1581
The String
middleman type conversion isn’t necessary if you use the unicodeScalars
property of Swift 4.0’s Character
type.
let myChar: Character = "3"
myChar.unicodeScalars.first!.value - Unicode.Scalar("0")!.value // 3: UInt32
This uses a trick commonly seen in C code of subtracting the value of the char
’0’
literal to convert from ascii values to decimal values. See this site for the conversions: https://www.asciitable.com
Also there are some implicit unwraps in my answer. To avoid those, you can validate that you have a decimal digit with CharacterSet.decimalDigits
, and/or use guard let
s around the first
property. You can also subtract 48 directly rather than converting ”0”
through Unicode.Scalar
.
Upvotes: 9
Reputation: 59496
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
}
Upvotes: 38