Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid escape sequence in literal: "\b"

I need to be able to create a String that is "\b". But when I try to, Xcode throws a compile-time error: Invalid escape sequence in literal. I don't understand why though, "\r" works just fine. If I put "\\b" then that's what is actually stored in the String, which is not what I need - I only need one backslash. To me, this seems to be a Swift oddity because it works just fine in Objective-C.

let str = "\b" //Invalid escape sequence in literal
NSString *str = @"\b"; //works great

I need to generate this string because "\b" is the only way to detect when the user pressed 'delete' when using UIKeyCommand:

let command = UIKeyCommand(input: "\b", modifierFlags: nil, action: "didHitDelete:")

How can I work around this issue?

EDIT: It really doesn't want to generate a String that is only "\b", this does not work - it stays the original value:

var delKey = "\rb"
delKey = delKey.stringByReplacingOccurrencesOfString("r", withString: "", options: .LiteralSearch, range: nil)
like image 903
Jordan H Avatar asked Dec 08 '14 01:12

Jordan H


1 Answers

The Swift equivalent of \b is \u{8}. It maps to ASCII control code 8, just like \b in Objective C. I've tested this and found it to work fine with UIKeyCommand, in this earlier answer of mine.

Example snippet:

func keyCommands() -> NSArray {
    return [
        UIKeyCommand(input: "\u{8}", modifierFlags: .allZeros, action: "backspacePressed")
    ]
}
like image 117
Matt Gibson Avatar answered Sep 26 '22 02:09

Matt Gibson