Iterate through alphabet in Swift

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)
    }

Tags:

Ios

Swift