如何获取数组元素中每个字符串的长度[" a"," a2"," b"," a2", " d"]就像" a"长度是1和" A2"长度是2.如何在swift中检查所有字符串的长度。
答案 0 :(得分:4)
您可以执行以下操作:
let result = ["a", "a2", "b", "a2", "d"].map {$0.count}
// result is [1, 2, 1, 2, 1]
答案 1 :(得分:0)
String.count
将为您完成工作......
var strArray = ["a", "a2", "b", "a2", "d"]
strArray.forEach { (str) in
print(str.count)
}
输出:
1 2 1 2 1
答案 2 :(得分:0)
// Swift 4x
for arr in array {
print(arr.count)
}
// Swift 3x
for arr in array {
print(arr.characters.count)
}
尝试上面的解决方案将获得所有元素计数,并且我已经在swift 3和swift 4中提供了解决方案。
答案 3 :(得分:-1)
var strArray = ["a", "a2", "b", "a2", "d"]
for(index, element) in strArray.enumerated()
{
print(element.count)
}
//输出:1 2 1 2 1