连接字符串

使用+运算符连接字符串以生成新字符串:

let name = "John"
let surname = "Appleseed"
let fullName = name + " " + surname  // fullName is "John Appleseed"

使用 += 复合赋值运算符或使用方法附加到可变字符串 :

let str2 = "there"
var instruction = "look over"
instruction += " " + str2  // instruction is now "look over there"

var instruction = "look over"
instruction.append(" " + str2)  // instruction is now "look over there"

在可变字符串中附加单个字符:

var greeting: String = "Hello"
let exclamationMark: Character = "!"
greeting.append(exclamationMark) 
// produces a modified String (greeting) = "Hello!"

将多个字符附加到可变字符串

var alphabet:String = "my ABCs: "
alphabet.append(contentsOf: (0x61...0x7A).map(UnicodeScalar.init)
                                         .map(Character.init) )
// produces a modified string (alphabet) = "my ABCs: abcdefghijklmnopqrstuvwxyz"

Version >= 3.0

appendContentsOf(_:) 已更名为 append(_:)

使用 joinWithSeparator(_:) 加入一串字符串以形成一个新字符串 :

let words = ["apple", "orange", "banana"]
let str = words.joinWithSeparator(" & ")

print(str)   // "apple & orange & banana"

Version >= 3.0

joinWithSeparator(_:) 已更名为 joined(separator:)

separator 默认是空字符串,所以 ["a", "b", "c"].joined() == "abc"