Invalid escape sequence in literal: "\ b"

I need to create String "\b" . But when I try, Xcode throws a compile-time error: Invalid escape sequence in literal. I do not understand why, however, "\r" works fine. If I put "\\b" , then what is actually stored in String is not what I need - I only need one backslash. For me, this seems like Swift weirdness because it works great in Objective-C.

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

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

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

How can I get around this problem?

EDIT: it really doesn’t want to generate a line that is only "\b" , this will not work - it remains the original value:

 var delKey = "\rb" delKey = delKey.stringByReplacingOccurrencesOfString("r", withString: "", options: .LiteralSearch, range: nil) 
+5
source share
2 answers

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

Fragment example:

 func keyCommands() -> NSArray { return [ UIKeyCommand(input: "\u{8}", modifierFlags: .allZeros, action: "backspacePressed") ] } 
+8
source

I do not believe this is supported.

Based on the Swift documentation https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html :

String literals can include the following Unicode special characters:

The special characters selected are \ 0 (null character), \ (backslash), \ t (horizontal tab), \ n (line), \ r (carriage return), \ "(double quote) and \ '(single quote)

An arbitrary Unicode scalar written as \ u {n}, where n is one to eight hexadecimal digits

ASCII for \ b - 8. If you do the following, you will see these results

 let bs = "\u{8}" var str = "Simple\u{8}string" println(bs) // Prints "" println("bs length is \(bs.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))") // Prints 1 println(str) // Prints Simplestring let space = "\u{20}" println(space) // Prints " " println("space length is \(space.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))") // Prints 1 str = "Simple\u{20}string" println(str) // Prints Simple string 

It appears that although ASCII 8 "exists", it is "ignored."

+3
source

Source: https://habr.com/ru/post/1208550/


All Articles