Rahul Chopra
Rahul Chopra

Reputation: 195

How to convert the string into ASCII Values in array and add those elements in Swift?

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
}

Upvotes: 1

Views: 3795

Answers (2)

Nilanshu Jaiswal
Nilanshu Jaiswal

Reputation: 1693

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

Upvotes: 4

jeanggi90
jeanggi90

Reputation: 761

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]

Upvotes: 3

Related Questions