Search code examples
swiftstring

Swift: generate an array of (Swift) characters


Simple question - hopefully, I am trying to generate a simple array of characters, something in the vein of:

// trying to do something like this (pseudo code):
let letters:[Character] = map(0..<26) { i in 'a' + i }

and have tried the following to no avail

let a = Character("a")
let z = Character("z")
let r:Range<Character> = a..<z
let letters:[Character] = map(a..<z) { i in i }

I realize that Swift uses Unicode, what is the correct way to do something like this?

(Note, this is not a question about interop with legacy Obj-C char, strictly in Swift for testing etc).


Solution

  • It's a little cumbersome to get the initial character code (i.e. 'a' in c / Obj-C) in Swift, but you can do it like this:

    let aScalars = "a".unicodeScalars
    let aCode = aScalars[aScalars.startIndex].value
    
    let letters: [Character] = (0..<26).map {
        i in Character(UnicodeScalar(aCode + i))
    }