Iterate through alphabet in Swift

前端 未结 8 1890
暗喜
暗喜 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:41

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-30 02:42
    for i in 97...122{println(UnicodeScalar(i))}
    
    0 讨论(0)
  • 2020-12-30 02:43

    Swift 4.2 version is much easier

    for char in "abcdefghijklmnopqrstuvwxyz" {
        print(char)
    }
    
    0 讨论(0)
  • 2020-12-30 02:49

    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

    0 讨论(0)
  • 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)
        }
    
    0 讨论(0)
  • 2020-12-30 02:59

    "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 */
    })
    
    0 讨论(0)
提交回复
热议问题