gpt4 book ai didi

swift - 在 Int swift 中转换 Char

转载 作者:行者123 更新时间:2023-11-28 10:03:27 25 4
gpt4 key购买 nike

我正在尝试将 char 转换为 int,在 C 中它可以工作,但在 Swift 中我遇到了一些问题。在 C 中不一样,使用 ascii 我没问题。

这个函数是我的 atoi 函数的一部分。

我尝试使用 binaryInt 和 UnicodeScalar,但没有成功

func scanNumber(_ strArray: [Character], _ index: Int, _ flag: Int) -> Int {

var resalt = 0

while ((strArray[index] >= "0") && (strArray[index] <= "9")) {
// flag mean plus or minus sign in strArray, if flag = 2 it's like a ["-", "1", "2", "3"]
if flag != 2 {
resalt *= 10
resalt = resalt + Int(strArray[index]) //error
} else {
resalt *= 10
resalt = resalt - Int(strArray[index]) //error
}
}
return resalt
}

Int(strArray[index]) 返回:

Initializer 'init(_:)' requires that 'Character' conform to 'BinaryInteger'

最佳答案

这是一个使用 asciiValue 的解决方案

func scanNumber(_ strArray: [Character], _ index: Int, _ flag: Int) -> Int {

var resalt = 0
var arrayIndex = index

while (arrayIndex < strArray.count && (strArray[arrayIndex] >= "0") && (strArray[arrayIndex] <= "9")) {
guard let ascii = strArray[arrayIndex].asciiValue else {
return resalt
}
resalt *= 10

if flag != 2 {
resalt += Int(ascii) - 48
} else {
resalt -= Int(ascii) - 48

}
arrayIndex += 1
}
return resalt
}

我也修复了循环

关于swift - 在 Int swift 中转换 Char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com