串联是指Swift中字符串的组合。字符串可能包含文本,整数,甚至表情符号!字符串连接有很多方法。让我列举一些:
相同的字符串
使用+ =
如果我们想要添加到一个已经存在的String,这是很有用的。为此,我们的String应该是可变的或可以修改的,因此将其声明为变量。例如:
var myClassmates = "John, Jane"
myClassmates += ", Mark" // add a new Classmate
// Result: "John, Jane, Mark"
不同的字符串
如果我们想把不同的字符串组合在一起,例如:
let oldClassmates = "John, Jane"
let newClassmate = "Mark"
我们可以使用以下任何一种:
1)使用+
let myClassmates = oldClassmates + ", " + newClassmate
// Result: "John, Jane, Mark"
注意,每个字符串可以是一个变量或常量。如果你只改变一次值,就把它声明为常量。
2)字符串插值
let myClassmates = "\(oldClassmates), \(newClassmate)"
// Result: "John, Jane, Mark"
3)添加
let myClassmates = oldClassmates.appending(newClassmate)
// Result: "John, Jane, Mark"
更多信息请参考Swift Book中的字符串和字符。
更新:在Swift 5.1上测试