Xcode – Invalid character in source file (Replace “ ” with “ ”)

I have a question about Xcode (Swift). Sometimes when I write an if statement. Something like this:

if(a == 2){
//do Sth
} else {
//do Sth

Xcode throws me an error: “Invalid character in source file”
I know it is no big deal and fixed by clicking on “Fix-it” but I want
to know what is the problem. That doesn’t make sense to me…

  • SpriteKit SKAction easing
  • How to Navigate from one View Controller to another using Swift
  • Continue uploading process in background IOS
  • How to format certain words of a cell's text label
  • Xcode 4.3 : missing icons for iOS apps in Organizer's archives
  • iOS: reload single cell of UICollectionView
  • Error

    My Xcode is on 7.2 and I am using Swift – I don’t know if this is just a Swift problem.

    3 Solutions Collect From Internet About “Xcode – Invalid character in source file (Replace “ ” with “ ”)”

    I was having this problem. The way I solved it is by 1) copying whatever you have into Sublime Text or another code editor and having a look (you may need to enable viewing hidden characters). Mine had a code in there DC2 which is some sort of ASCII control character. For me it was caused by the fact that I had put the playground into manual execute and bound a keyboard shortcut to it that seemed to be entering that control character every time I executed it using the shortcut. I just changed the shortcut and removed the ASCII characters as I was able to see them in Sublime Text. (The link in the comments to the OP concerning left to right mode made no sense and didn’t work for me.)

    I encountered this problem when I was using a non-Apple keyboard with my iMac. Probably your case too. They add unnecessary control characters! One way to fix it in Xcode ischoose from the menu Editor>Show Invisibles and see if there are any unwanted characters where the error is being thrown and remove them.

    Editor->Show Invisibles did not show the character that was causing a problem for me. No-break-space (u00a0) will be shown as a space with no “dot” indicator. However, that’s really hard to see and I completely missed it the first time. Zoom helps.

    One way I found to detect invalid characters is to use Visual Studio Code and enable the settings:

    “editor.renderControlCharacters”: true
    “editor.renderWhitespace”: “all”

    This has the same visibility issue with no-break-space as Xcode, however it does show other special characters.

    To make it more obvious and possibly detect more invalid characters, install the extension “ascii-unicode-escape” and follow the instructions.

    I don’t understand why Xcode allows these invalid characters, inserts them into your source files for no reason, and doesn’t even give an option to detect them! I’m trying to write code, not secrets in invisible ink, damnit!! I guess it’s less of an issue for compiled code, which will show an error, but not so convenient with shader code.