我有一个数组。我尝试分析每个元素(每个元素是一个字符)并比较每个元素是否单独等于另一个字符,如下所示:
(以下代码不正确,仅供说明)
let array = ["5","a","5","8","l","j"]
var finalString = ""
for i in array {
if array[i] = ["^0-9"] {
//Compares if the element in position i is equal to a number between 0 - 9
finalString + "1 " //or do something else
} else if array[i] = ["^a-z"] {
//Compares if the element in position i is equal to a character between a - z
finalString + "2 " //or do something else
}
}
print(finalString)
//Expected output
// 1 2 1 1 2 2
我希望我的问题的解释清楚。
答案 0 :(得分:3)
我想了解更多有关可能的输入值的信息。
let array = ["5","a","5","8","l","j"]
let finalString = array.reduce("") { result, character in
switch character {
case "0"..."9": return result.appending("1 ")
case "a"..."z": return result.appending("2 ")
default: assertionFailure("\(character) is unexpected input"); return result
}
}
print(finalString)
答案 1 :(得分:1)
你有几个问题。以下代码清除了这些问题,并使用CharacterSet
查看数组元素是否包含数字或字母。
let array = ["5","a","5","8","l","j"]
var finalString = ""
for str in array {
if str.rangeOfCharacter(from: .decimalDigits) != nil {
//Compares if the string contains any digits
finalString += "1 " //or do something else
} else if str.rangeOfCharacter(from: .letters) != nil {
//Compares if the string contains any letters
finalString += "2 " //or do something else
} else {
finalString += "0 " //or do something else
}
}
print("Res: \(finalString)")
输出:
分辨率:1 2 1 1 2 2
这些特定检查与您在代码中提到的检查略有不同,但对于您的示例,它会给出相同的结果。
如果您只想接受0-9或a-z,则需要更新正在使用的特定字符集。