0

I'm trying to figure out how to obtain the numeric value of characters that are contained in a String object.

e.g.

let checkString = "ball"
for i in checkString.characters {
    var val = Int(String(i))!
    print(val)
}

I would like my output to be:

ASCII value of 'b'
ASCII value of 'a'
ASCII value of 'l'
ASCII value of 'l'

However, I get instead the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

In Java, the equivalent code is:

int val = str.charAt(i)

Can anyone see where it is I'm going wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
syedfa
  • 2,801
  • 1
  • 41
  • 74

1 Answers1

0

Based on this post What's the simplest way to convert from a single character String to an ASCII value in Swift? you could try this:

extension String {
    var asciiArray: [UInt32] {
        return unicodeScalars.filter{$0.isASCII}.map{$0.value}
    }
}

extension Character {
    var asciiValue: UInt32? {
        return     String(self).unicodeScalars.filter{$0.isASCII}.first?.value
    }
}

"ball".lowercased().asciiArray.forEach { print($0 - 96) }

Notice this will only work for lowered case string since the calculation is ASCII based, therefore 97 equals "a", 98 "b" and so on. If you want to adapt it to upper case strings you would need to use this line instead:

"UPpER".uppercased().asciiArray.forEach { print($0 - 64) }
Mauricio Chirino
  • 1,182
  • 17
  • 19