Home » Swift » How to deal with a user input string that gives an “unprintable ascii character found in source file” error when pasted into Xcode?

How to deal with a user input string that gives an “unprintable ascii character found in source file” error when pasted into Xcode?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am working on an app that lets the user paste in text and then the app processes that text.

With a certain text string I am getting an “unprintable ascii character found in source file” error. The unprintable character appears to be a tab, but I’m not sure. Anyway, it is causing problems when I try to process the text.

How can I filter out this or other unprintable characters when I first save the string in a variable?

Or is there another way to deal with this?

Answers:

Here’s another way to do it.

This version also allows new line characters.

func convertString(string: String) -> String {
  var data = string.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
  return NSString(data: data!, encoding: NSASCIIStringEncoding) as! String
}

Questions:
Answers:

If you are only interested in keeping printable ASCII characters, then this code should work.

extension String {
    func printableAscii() -> String {
        return String(bytes: filter(self.utf8){$0 >= 32}, encoding: NSUTF8StringEncoding) ?? ""
    }
}

Note this will filter tabs and line feeds too which may not be expected. Unprintable ASCII are any values less than 0x20. Here is a Playground screen capture.

enter image description here