in Obj-C it was possible to iterate through alphabet with:
for (char x=\'A\'; x<=\'Z\'; x++) {
In Swift this isn\'t possible. Any idea h
Updated for Swift 3.0 and higher
let startChar = Unicode.Scalar("A").value
let endChar = Unicode.Scalar("Z").value
for alphabet in startChar...endChar {
if let char = Unicode.Scalar(alphabet) {
print(char)
}
}
for i in 97...122{println(UnicodeScalar(i))}
Swift 4.2 version is much easier
for char in "abcdefghijklmnopqrstuvwxyz" {
print(char)
}
Did you try this one ?
for var myChar:CChar = 65 ; myChar <= 90 ; ++myChar {
let x:String = String(format: "%c", myChar)
println(x)
}
If you already know the character code
It's slightly cumbersome, but the following works (Swift 3/4):
for value in UnicodeScalar("a").value...UnicodeScalar("z").value { print(UnicodeScalar(value)!) }
I suspect that the problem here is that the meaning of "a"..."z" could potentially be different for different string encodings.
(Older stuff)
Also cumbersome, but without the extra intermediate variable:
for letter in map(UnicodeScalar("a").value...UnicodeScalar("z").value, {(val: UInt32) -> UnicodeScalar in return UnicodeScalar(val); })
{
println(letter)
}
"Pure functional" Swift 5 way:
(Unicode.Scalar("A").value...Unicode.Scalar("Z").value).forEach({
let letter = Unicode.Scalar($0)!
print(letter)
/* do other stuff with letter here */
})