0

How I can handle this error, I try to get ascii number of every character in string but I can't convert character back to string in order to check symbol whether it necessary?

Here is my code

var n = "KNjNKJbbsibdcjkdcn___*(&0786"
let r = n.characters.count

for i in stride(from: 0, to: r, by: 1) {
    let t = n.characters.index(n.startIndex, offsetBy: i)

    String?(n[t])
}

In output should be separated character in string type.

antoshkaaa
  • 11
  • 2
  • 1
    The only problem is the stray question mark in the expression `String?(n[t])` (that and not doing anything with the result). But anyway, you can just do `for character in n.characters {...}` – compare [Iterate through a String Swift 2.0](http://stackoverflow.com/q/30767594/2976878). Otherwise, your current implementation will run in quadratic (not linear) time. – Hamish May 15 '17 at 20:01
  • 1
    Just `for character in n.characters { let str = String(character) }` – Hamish May 15 '17 at 20:10
  • I just ran it through a Playground getting rid of the `?` and it worked fine. – Pierce May 15 '17 at 20:12

1 Answers1

0

This bit of code will convert a string to an array of ASCII characters (excluding those with no ASCII code):

let str = "KNjNKJbbsibdcjkdcn___*(&0786"
let charCodes = str.unicodeScalars
    .filter({ $0.isASCII })
    .map({ $0.value })
print(charCodes)
Josh at The Nerdery
  • 1,397
  • 9
  • 16