Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through alphabet in Swift

Tags:

ios

swift

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?

like image 416
Lupurus Avatar asked Jun 03 '14 16:06

Lupurus


People also ask

How do you loop through each character in a string Swift?

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.

Can you loop through a string in Swift?

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.

How do I print a character string in Swift?

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.


4 Answers

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.

like image 74
Logan Avatar answered Nov 05 '22 16:11

Logan


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)
    }
like image 27
ipmcc Avatar answered Nov 05 '22 18:11

ipmcc


for i in 97...122{println(UnicodeScalar(i))}
like image 43
Chéyo Avatar answered Nov 05 '22 18:11

Chéyo


Swift 4.2 version is much easier

for char in "abcdefghijklmnopqrstuvwxyz" {
    print(char)
}
like image 22
Tung Vu Duc Avatar answered Nov 05 '22 16:11

Tung Vu Duc