如何将字符串转换为数组中的ASCII值并在Swift中添加这些元素?

时间:2017-11-15 09:08:31

标签: swift

如何将此字符串“RAHUL”转换为数组中的ASCII值并添加数组的所有元素。

StartCoroutine(RotateCoroutine(new Vector3(0,90,0), 2.0f));

2 个答案:

答案 0 :(得分:1)

尝试一下

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

如果要添加值

let sum = asciiValues.reduce(0, { Int($0) + Int($1) })
print(sum) // 380

答案 1 :(得分:0)

只需将num转换为Int并将其添加到数组中:

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]