Iterate through alphabet in Swift

前端 未结 8 1892
暗喜
暗喜 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 03:00

    This solution works with Swift 3.0, and will either print out the values per OP request:

    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.flatMap { print($0) }
    

    Or provide you with an array of letters:

    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.flatMap { $0.description }
    
    0 讨论(0)
  • 2020-12-30 03:04

    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.

    0 讨论(0)
提交回复
热议问题