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 how I could do this?
To loop or iterate over every character in a String in Swift, we can use for-in statement with String. During each iteration we get the access to this character in the loop body.
You can loop through every character in a string by treating it as an array. Thanks to Swift's extended support for international languages and emoji, this works great no matter what kind of language you're using.
Overview. Printing the characters of a string value in Swift using the forEach function or loop is easy. The forEach function iterates over the string and repeats an action—in this case, it prints the character—for each element of the string.
In Swift, you can iterate chars on a string like this:
Swift 2
for char in "abcdefghijklmnopqrstuvwxyz".characters {
println(char)
}
Swift 1.2
for char in "abcdefghijklmnopqrstuvwxyz" {
println(char)
}
There might be a better way though.
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)
}
for i in 97...122{println(UnicodeScalar(i))}
Swift 4.2 version is much easier
for char in "abcdefghijklmnopqrstuvwxyz" {
print(char)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With