Swift 文档学习——字符串和字符
官方文档(英文):https://docs.swift.org/swift-book/documentation/the-swift-programming-language/
官方文档(中文):https://swiftgg.gitbook.io/swift/
1、字符串字面量
(1)多行字符串字面量
续行符:反斜杠(\)。
let softWrappedQuotation = """
The White Rabbit put on his spectacles. "Where shall I begin, \
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""
(2)字符串字面量的特殊字符
转义字符 \0(空字符)、\(反斜线)、(水平制表符)、(换行符)、(回车符)、"(双引号)、'(单引号)。
Unicode 标量,写成 \u{n}(u 为小写),其中 n 为任意一到八位十六进制数且可用的 Unicode 位码。
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}" // $,Unicode 标量 U+0024
let blackHeart = "\u{2665}" // ♥,Unicode 标量 U+2665
let sparklingHeart = "\u{1F496}" // 💖,Unicode 标量 U+1F496
在多行字符串字面量用"“” “”“来表示字符串内容时,(”)则不用转义字符(\),但是里面有(“”")时,需要至少一个转义字符(\),如:
let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""
(3)扩展字符串分隔符
let string1 = #"Line 1 \nLine 2"#
// 输出 Line 1 \nLine 2
let string2 = #"Line 1 \#nLine 2"#
// 输出 Line1
// Line2
let string3 = ###"Line1 \###nLine2"###
// 输出 Line1
// Line2
2、初始化空字符串
var emptyString = "" // 空字符串字面量
var anotherEmptyString = String() // 初始化方法
// 两个字符串均为空并等价。
if emptyString.isEmpty {
print("Nothing to see here")
}
// 打印输出:“Nothing to see here”
3、字符串可变性
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// 这会报告一个编译错误(compile-time error) - 常量字符串不可以被修改。
4、字符串是值类型
Swift 默认拷贝字符串的行为保证了在函数/方法向你传递的字符串所属权属于你,无论该值来自于哪里。你可以确信传递的字符串不会被修改,除非你自己去修改它。
5、使用字符串
for character in "Dog!🐶" {
print(character)
}
// D
// o
// g
// !
// 🐶
let catCharacters: [Character] = ["C", "a",