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

可紊 提交于 2019-11-26 22:54:46

For that and also future reference:

\0 – 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)

It will print I love my "country"

Use the following code for Swift 5, Xcode 10.2

let myText = #"This is a Backslash: \"#
print(myText)

Output:

This is a Backslash: \

Now not required to add a double slash to use a single slash in swift 5, even now required slash before some character, for example, single quote, double quote etc.

See this post for latest update about swift 5

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

The backslash character \ acts as an escape character when used in a string. This means you can use, for example, double quotes, in a string by pre-pending them with \. The same also applies for the backslash character itself, which is to say that println("\\") will result in just \ being printed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!