Jor*_*n H 6 string escaping ios swift
我需要能够创建一个String "\b".但是当我尝试时,Xcode会抛出编译时错误:文字中的转义序列无效.我不明白为什么,但"\r"工作得很好.如果我把"\\b"那就是实际存储在String中的东西,这不是我需要的东西 - 我只需要一个反斜杠.对我来说,这似乎是一个Swift古怪,因为它在Objective-C中运行得很好.
let str = "\b" //Invalid escape sequence in literal
NSString *str = @"\b"; //works great
Run Code Online (Sandbox Code Playgroud)
我需要生成这个字符串,因为这"\b"是检测用户何时使用"删除"的唯一方法UIKeyCommand:
let command = UIKeyCommand(input: "\b", modifierFlags: nil, action: "didHitDelete:")
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
编辑:它真的不想生成一个只有的字符串"\b",这不起作用 - 它保持原始值:
var delKey = "\rb"
delKey = delKey.stringByReplacingOccurrencesOfString("r", withString: "", options: .LiteralSearch, range: nil)
Run Code Online (Sandbox Code Playgroud)
的雨燕相当于\b是\u{8}.它映射到ASCII控制代码8,就像\b在Objective C中一样.我已经测试过这个并且发现它可以正常工作UIKeyCommand,在我之前的这个答案中.
示例代码段:
func keyCommands() -> NSArray {
return [
UIKeyCommand(input: "\u{8}", modifierFlags: .allZeros, action: "backspacePressed")
]
}
Run Code Online (Sandbox Code Playgroud)
我不相信它得到支持。
字符串文字可以包含以下特殊的 Unicode 字符:
转义的特殊字符 \0(空字符)、\(反斜杠)、\t(水平制表符)、\n(换行)、\r(回车)、\"(双引号)和 \'(单引号)
任意 Unicode 标量,写作 \u{n},其中 n 介于 1 到 8 个十六进制数字之间
\b 的 ASCII 是 8。如果您执行以下操作,您将看到这些结果
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
Run Code Online (Sandbox Code Playgroud)
看起来虽然 ASCII 8“存在”,但它被“忽略”。
| 归档时间: |
|
| 查看次数: |
6272 次 |
| 最近记录: |