gpt4 book ai didi

arrays - 如何迭代数组并将每个元素与 Swift 中的其他元素进行比较

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

我有一个数组。我尝试分析每个元素(每个元素都是一个字符)并比较每个元素是否单独等于另一个字符,如下所示:

(以下代码不正确,仅作说明)

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

我希望我的问题的解释很清楚。

最佳答案

我想了解有关可能的输入值的更多信息。

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)

关于arrays - 如何迭代数组并将每个元素与 Swift 中的其他元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565814/

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