Swift 创建和初始化字符串
2021-07-28 本文已影响0人
_发强
初始化空串
1, 字面量
- 单行字面量
var emptyString = "" // Swift 会反向推理 emtpyString 为字符串类型,
- 多行字面量
-
多行字面量时用 三个双引号引起来的一系列字符
-
多行字面量,就是你引起来的内容是什么样,输出的时候就是什么样。
-
三个引号一定是单独存在一行的,不然编译器报错。
注意:开头和结尾的默认不会有换行符。
-
如果你的内容过长,你想换行,但是又不想让换行出现在内容中, 那就在行末 添加一个反斜杠( \ )
`
示例1:
// 多行字面量
let strMultiLine = """
I am Grout,I am Grout,I am Grout,I am Grout,I am Grout。
My name is Grout,My name is Grout,My name is Grout,My name is Grout,My name is Grout,
I'm a boy.
"""
print(strMultiLine)
输出内容:
I am Grout,I am Grout,I am Grout,I am Grout,I am Grout。
My name is Grout,My name is Grout,My name is Grout,My name is Grout,My name is Grout,
I'm a boy.

示例2:
// 多行字面量
let strMultiLine = """
I am Grout,I am Grout,I am Grout,I am Grout,I am Grout。
My name is Grout,My name is Grout,\
My name is Grout,My name is Grout,\
My name is Grout,
I'm a boy.
"""
print(strMultiLine)
I am Grout,I am Grout,I am Grout,I am Grout,I am Grout。
My name is Grout,My name is Grout,My name is Grout,My name is Grout,My name is Grout,
I'm a boy.
输出结果是和代码1 一样的,这里是为了验证多行字面量的第 4 条。

- 多行字符串,每一行开头的内容不得超出结束时的 三个引号,空格区域也是以结束的三个引号为参照的。
实例:
let strMultiLine = """
I am Grout,I am Grout,I am Grout,I am Grout,I am Grout。
My name is Grout,My name is Grout,\
My name is Grout,My name is Grout,\
My name is Grout,
I'm a boy.
"""


2, 初始化器语法
var emtpyString = String()
```,