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).
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.
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.
You can create an empty array by specifying the Element type of your array in the declaration.
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(_:)
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With