gpt4 book ai didi

ios - Swift4 将特定字符串转换为特定 Int

转载 作者:搜寻专家 更新时间:2023-11-01 05:49:25 24 4
gpt4 key购买 nike

喜欢我的问题标题。
如果我得到 A,我想返回 0。
如果我得到 B,我想返回 1。
....
如果我得到 Z,我想返回 25。
如何让这个功能看起来更好更简单?谢谢。

func convertStringToInt(text: String) -> Int {

switch text {
case "A":
return 0
case "B":
return 1

//...C TO Y

case "Z":
return 25
default:
break
}
return 0

}

最佳答案

使用 ASCII 值,您可以将其缩短为(也适用于小写):

func convertStringToInt(characterText: String) -> Int? {
guard let aValue = "A".unicodeScalars.first?.value,
let zValue = "Z".unicodeScalars.first?.value,
let characterValue = characterText.uppercased().unicodeScalars.first?.value,
// next line tests if the input value is between A and Z
characterValue >= aValue && characterValue <= zValue else {
return nil // error

}
return Int(characterValue) - Int(aValue)
}

print("Value for A: \(convertStringToInt(characterText: "A"))")
print("Value for G: \(convertStringToInt(characterText: "G"))")
print("Value for Z: \(convertStringToInt(characterText: "Z"))")
print("Value for z: \(convertStringToInt(characterText: "z"))")
print("Value for ^: \(convertStringToInt(characterText: "^"))")

打印:

Value for A: Optional(0)
Value for G: Optional(6)
Value for Z: Optional(25)
Value for z: Optional(25)
Value for ^: nil

基于 this question .

或者,如果您想使用数组索引:

func convertStringToInt(characterText: String) -> Int {
let array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
return array.firstIndex(of: characterText.uppercased()) ?? -1 // default value for a text that is not found
}

关于ios - Swift4 将特定字符串转换为特定 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52365659/

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