简体   繁体   English

在Swift中将字符转换为整数

[英]Convert Character to Integer in Swift

I am creating an iPhone app and I need to convert a single digit number into an integer. 我正在创建一个iPhone应用程序,我需要将单个数字转换为整数。

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. 我的代码有一个名为char的变量,它有一个Character类型,但是我需要能够用它做数学,因此我认为我需要将它转换为字符串,但是我找不到办法做到这一点。

With a Character you can create a String . 使用Character您可以创建一个String And with a String you can create an Int . 使用String您可以创建一个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. 如果使用Swift 4.0的Character类型的unicodeScalars属性,则不需要String中间人类型转换。

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. 这使用了C代码中常见的一种技巧,即减去char '0'文字的值,以便将ascii值转换为十进制值。 See this site for the conversions: https://www.asciitable.com 有关转换,请访问此网站: 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. 要避免这些,您可以使用CharacterSet.decimalDigits验证您是否有十进制数字,和/或在第first属性周围使用guard let s。 You can also subtract 48 directly rather than converting ”0” through Unicode.Scalar . 您也可以直接减去48而不是通过Unicode.Scalar转换”0”

In the latest Swift versions (at least in Swift 5) there is a more straighforward way of converting Character instances. 在最新的Swift版本中(至少在Swift 5中),有一种更直接的转换Character实例的方法。 Character has property wholeNumberValue which tries to convert a character to Int and returns nil if the character does not represent and integer. Character具有属性wholeNumberValue ,它尝试将字符转换为Int ,如果字符不表示整数,则返回nil

let char: Character = "5"
if let intValue = char.wholeNumberValue {
    print("Value is \(intValue)")
} else {
    print("Not an integer")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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