初始化空字符串 (Initializing an Empty String)
要创建一个空字符串作为初始值,可以将空的字符串字面量赋值给变量,也可以初始化一个新的String实例:
var emptyString = "" // 空字符串字面量
var anotherEmptyString = String() // 初始化方法
// 两个字符串均为空并等价。
字符串可变性 (String Mutability)
通过将一个特定字符串分配给一个变量来对其进行修改,或者分配给一个常量来保证其不会被修改:
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// 这会报告一个编译错误 (compile-time error) - 常量字符串不可以被修改。
在 Objective-C 和 Cocoa 中,需要通过选择两个不同的类(NSString和NSMutableString)来指定字符串是否可以被修改。
字符串是值类型(Strings Are Value Types)
Swift 的String类型是值类型。 如果创建了一个新的字符串,那么当其进行常量、变量赋值操作,或在函数/方法中传递时,会进行值拷贝。 任何情况下,都会对已有字符串值创建新副本,并对该新副本进行传递或赋值操作。 值类型在 结构体和枚举是值类型 中进行了详细描述。
Swift 默认字符串拷贝的方式保证了在函数/方法中传递的是字符串的值。 很明显无论该值来自于哪里,都是独自拥有的。
在实际编译时,Swift 编译器会优化字符串的使用,使实际的复制只发生在绝对必要的情况下,这意味着字符串作为值类型的同时可以获得极高的性能。
使用字符(Working with Characters)
通过for-in循环来遍历字符串中的characters属性来获取每一个字符的值:
for character in "Dog!".characters {
print(character)
}
// D
// o
// g
// !
//
连接字符串和字符 (Concatenating Strings and Characters)
字符串可以通过加法运算符(+)相加在一起(或称“连接”)创建一个新的字符串:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome 现在等于 "hello there"
可以通过加法赋值运算符 (+=) 将一个字符串添加到一个已经存在字符串变量上:
var instruction = "look over"
instruction += string2
// instruction 现在等于 "look over there"
可以用append()方法将一个字符附加到一个字符串变量的尾部:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome 现在等于 "hello there!"
字符串插值 (String Interpolation)
字符串插值是一种构建新字符串的方式,可以在其中包含常量、变量、字面量和表达式。 插入的字符串字面量的每一项都在以反斜线为前缀的圆括号中:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
插值字符串中写在括号中的表达式不能包含非转义反斜杠 (),并且不能包含回车或换行符。不过,插值字符串可以包含其他字面量。
比较字符串 (Comparing Strings)
Swift 提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。
字符串/字符相等 (String and Character Equality)
字符串/字符可以用等于操作符(==)和不等于操作符(!=),详细描述在比较运算符:
let a = "Ww"
let b = "Ww"
if a == b {
print("These two strings are considered equal")
}
// 打印输出 "These two strings are considered equal"
前缀/后缀相等 (Prefix and Suffix Equality)
通过调用字符串的hasPrefix(:)/hasSuffix(:)方法来检查字符串是否拥有特定前缀/后缀,两个方法均接收一个String类型的参数,并返回一个布尔值。
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// 打印输出 "There are 5 scenes in Act 1"
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// 打印输出 "6 mansion scenes; 2 cell scenes"