-3

I want to convert alphabets to numbers, in this way: a=0, b=1, c=2 ... z=25 in Swift. I have an array of integers range 0-25. I want to get alphabets from the Int array. If I have an array of characters, how can I get an array of Int?

David S
  • 55
  • 7

2 Answers2

2
//Create an array of UInt8 vaues:
var array = [UInt8]()
for _ in 1...20 {
    array.append(UInt8.random(in: 0...25))
}

//Now map the array of values to characters 'a' to 'z'
let charArray = array.map {UnicodeScalar($0 + (Character("a").asciiValue ?? 0))}

charArray.forEach { print($0) }

//Now map the char array back to int values

let valueOfA = Character("a").asciiValue ?? 0
let charToUIntArray = charArray.map { (Character($0).asciiValue ?? 0) - valueOfA}
Duncan C
  • 128,072
  • 22
  • 173
  • 272
-1

How to get string from ASCII code in Swift?

You can make your numbers match the right characters if you add an offset to your numbers and assign this number with the Character initializer to your character.

func getChar(number: Int)->Character{
    return Character(UniCodeScalar(number+97))
}

The other way around you can use the asciiValue property.

(What's the simplest way to convert from a single character String to an ASCII value in Swift?)

After that you can loop through the array and use for example functions to convert.

sheldor
  • 115
  • 12
  • What is the problem with the answer? – sheldor May 17 '21 at 20:45
  • Link only answers are discouraged. While a link may link to an important resource, you should add the relevant parts to your answer (not necessarily removing the link). In that case if the link ever changes or goes offline, your answer will still be valuable. – Andy Ibanez May 17 '21 at 21:22