(Swift) 如何在字符串中打印“\”字符?

(Swift) how to print "\" character in a string?

我曾尝试打印它,但由于它是一个转义字符,所以只能通过传递。 例如输出应如下所示。

\correct

反斜杠字符 \ 在字符串中用作转义字符。这意味着您可以在字符串中使用双引号,方法是在它们前面加上 \。这同样适用于反斜杠字符本身,也就是说 println("\") 将导致只打印 \

为此以及未来的参考:

[=10=] – Null character (that is a zero after the slash)
\ – Backslash itself.  Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t  – Horizontal tab
\n – Line Feed
\r  – Carriage Return
\”  – Double quote.  Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’  – Single Quote.  Similar reason to above.
var s1: String = "I love my "
 let s2: String = "country"
   s1 += "\"\(s2)\""
   print(s1)

它会打印 I love my "country"

Swift5、Xcode10.2

使用以下代码
let myText = #"This is a Backslash: \"#
print(myText)

输出:

This is a Backslash: \

现在在swift5中不需要添加双斜杠来使用单斜杠,即使现在需要在某些字符前添加斜杠,例如单引号、双引号等

有关 swift 5

的最新更新,请参阅此 post

https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0