初始化空串
- 字面量
- 初始化器语法
- isEmpty 检查是否为空串
var emptyString = ""
var anotherEmptyString = String()
if emptyString.isEmpty {
print("Nothing to see here")
}
字面量
- 字符串字面量是被双引号(")包裹的固定顺序文本字符
- Swift 会为 str 常量推断类型为 String
let str = "Hello, playground"
多行字面量
- 多行字符串字面量是用三个双引号引起来的一系列字符
- 多行字符串字面量把所有行包括在引号内,开始和结束默认不会有换行符
- 当你的代码中在多行字符串字面量里包含了换行,那个换行符同样会成为字符串里的值。如果你想要使用换行符来让你的代码易读,却不想让换行符成为字符串的值,那就在那些行的末尾使用反斜杠(\)
let softWrappedQuotation = """
The white Rabbit put on his spectacles. "where shall I began, please your Majesty ?" he asked.
"Began at the baginning," the King said gravely, "and go on till you come to the end; then stop."
"""
print(softWrappedQuotation)
打印结果如下:
The white Rabbit put on his spectacles. "where shall I began, please your Majesty ?" he asked.
"Began at the baginning," the King said gravely, "and go on till you come to the end; then stop."
使用反斜杠
let softWrappedQuotation = """
The white Rabbit put on his spectacles. "where shall I began,\
please your Majesty ?" he asked.
"Began at the baginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""
print(softWrappedQuotation)
打印结果如下:
The white Rabbit put on his spectacles. "where shall I began,please your Majesty ?" he asked.
"Began at the baginning," the King said gravely, "and go on till you come to the end; then stop."
多行字面量
- 要让多行字符串字面量起始于或者结束于换行,就在第一或最后一行写一个空行
- 多行字符串可以锁进以匹配周围的代码。双引号(" " ")前的空格会告诉Swift 其他行前应该有多少空白是需要忽略的。
-
如果你在某行的空格超过了结束的双引号(" " "),那么这些空格会被包含。
多行字面量.png
字符串里的特殊字符串
- 转义字符 \0(空字符),\(反斜杠),\t(水平制表符),\n(换行符),\r(回车符),\“(双引号)\‘(单引号)
- 任意的Unicode 标量,写作 \u{n},里边的 n 是一个 1-8 位的16进制数字,其值是合法 Unicode 值
-
可以在多行字符串字面量中包含双引号(")而不需要转义。要在多行字符串中包含文本(""")转义至少一个双引号
特殊字符.png
扩展字符串分隔符(Raw String)
Swift 5 新增的特性
- 在字符串字面量中放置扩展分隔符来在字符串中包含特殊字符而不让他们真的生效
- 把字符串放在双引号(“)内并由井号(#)包裹
- 如果字符串里有”#则首尾需要2个#
- 如果需要字符串中某个特殊符号的效果,使用匹配你包裹的井号数量的井号并在前面写转义符号
扩展字符串分隔符.png
网友评论