0

How to convert this string "RAHUL" into ASCII Values in array and adding all the elements of array.

var myString: String = "RAHUL"

for scalar in myString.unicodeScalars 
{
    print(scalar.value)
    var num = scalar.value
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
Rahul Chopra
  • 187
  • 1
  • 13
  • 2
    Possible duplicate of [What's the simplest way to convert from a single character String to an ASCII value in Swift?](https://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va) – Hamish Nov 15 '17 at 10:16

2 Answers2

4

Try this

var myString = "RAHUL"
let asciiValues = myString.compactMap { $0.asciiValue }
print(asciiValues) // [82, 65, 72, 85, 76]

If you want to add the values

let sum = asciiValues.reduce(0, { Int($0) + Int($1) })
print(sum) // 380
Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
2

Just convert the num to a Int and add them to an array:

var myString: String = "RAHUL"
var asciiArray = [Int]()

for scalar in myString.unicodeScalars 
{
    var num = Int(scalar.value)
    asciiArray.append(num)
}

print(asciiArray)    //Prints [82, 65, 72, 85, 76]
jeanggi90
  • 741
  • 9
  • 24