我想在以下字符串中计算字母,数字和特殊字符的数量:
let phrase = "The final score was 32-31!"
我试过了:
for tempChar in phrase { if (tempChar >= "a" && tempChar <= "z") { letterCounter++ } // etc.
但我收到错误。我尝试了各种其他变体 – 仍然会收到错误 – 例如:
could not find an overload for '<=' that accepts the supplied arguments
任何线索?
可能的Swift解决方案:
var letterCounter = 0 var digitCount = 0 let phrase = "The final score was 32-31!" for tempChar in phrase.unicodeScalars { if tempChar.isAlpha() { letterCounter++ } else if tempChar.isDigit() { digitCount++ } }
更新:上述解决方案仅适用于ASCII字符集中的字符,
即不识别Ä,é或ø为字母。以下替代方案
解决方案从Foundation框架中使用NSCharacterSet,它可以测试字符
基于他们的Unicode字符类:
let letters = NSCharacterSet.letterCharacterSet() let digits = NSCharacterSet.decimalDigitCharacterSet() var letterCount = 0 var digitCount = 0 for uni in phrase.unicodeScalars { if letters.longCharacterIsMember(uni.value) { letterCount++ } else if digits.longCharacterIsMember(uni.value) { digitCount++ } }
更新2:从Xcode 6 beta 4开始,第一个解决方案不再工作,因为
从Swift中删除了isAlpha()和相关(仅限ASCII)的方法。
第二个解决方案仍然可行。
Swift 3的更新:
let letters = CharacterSet.letters let digits = CharacterSet.decimalDigits var letterCount = 0 var digitCount = 0 for uni in phrase.unicodeScalars { if letters.contains(uni) { letterCount += 1 } else if digits.contains(uni) { digitCount += 1 } }