Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 532
Chris Conover Avatar asked Oct 01 '14 23:10

Chris Conover


People also ask

How do you create an array of strings in Swift?

Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets. Without any other information, Swift creates an array that includes the specified values, automatically inferring the array's Element type.

How do you declare an array in Swift?

We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it's an array of integers.

How do you create an empty array in Swift?

You can create an empty array by specifying the Element type of your array in the declaration.

How do I map an array in Swift?

We can use the map(_:) method to transform the elements of the array. I would like to create an array that contains the number of characters of each string in the array. We invoke map(_:) on strings and pass a closure to the map(_:)


1 Answers

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))
}
like image 179
Mike S Avatar answered Sep 28 '22 06:09

Mike S