Swift連接字符串和字符
連接字符串和字符 (Concatenating Strings and Characters)
字符串和字符的值可以通過加法運算符(+
)相加在一起並創建一個新的字符串值:
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // 等於 "hello!"
let stringPlusString = string1 + string2 // 等於 "hello there"
let characterPlusString = character1 + string1 // 等於 "!hello"
let characterPlusCharacter = character1 + character2 // 等於 "!?"
您也可以通過加法賦值運算符 (+=
) 將一個字符串或者字符添加到一個已經存在字符串變量上:
var instruction = "look over"
instruction += string2
// instruction 現在等於 "look over there"
var welcome = "good morning"
welcome += character1
// welcome 現在等於 "good morning!"
注意:
您不能將一個字符串或者字符添加到一個已經存在的字符變量上,因為字符變量隻能包含一個字符。