Iterate through alphabet in Swift

前端 未结 8 1941
暗喜
暗喜 2020-12-30 02:23

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

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 02:51

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

提交回复
热议问题