简体   繁体   中英

Convert Character to Integer in 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.

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    
}

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 .

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM