Swift 字串與字元 (Strings and Characters)
Swift 的 String 類型是用來處理文字資料的強大工具。Swift 的 String 與 Foundation 框架中的 NSString 是可以無縫橋接 (Bridged) 的,這意味著你可以在 String 上使用所有 NSString 的方法。
字串字面量 (String Literals)
使用雙引號 "" 來定義字串。
let someString = "有些字串"
多行字串字面量
如果你需要定義跨越多行的字串,可以使用三個雙引號 """:
let quotation = """
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."
"""
字串操作
初始化空字串
var emptyString = "" // 空字串字面量
var anotherEmptyString = String() // 初始化語法
// 兩者是等價的
檢查字串是否為空:
if emptyString.isEmpty {
print("什麼都沒有")
}
字串可變性 (Mutability)
透過宣告為 var (可變) 或 let (不可變) 來決定字串是否可以修改。這與 Objective-C 中區分 NSString 和 NSMutableString 不同。
var variableString = "Horse"
variableString += " and carriage"
// variableString 現在是 "Horse and carriage"
let constantString = "Highlander"
// constantString += " and another Highlander"
// 錯誤!常數不能被修改
字串串接
最簡單的方法是使用 + 運算子:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome 等於 "hello there"
字串插值 (String Interpolation)
這是建構新字串最直觀的方式。在字串中包入 \(expression):
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message 等於 "3 times 2.5 is 7.5"
計算字元數量
使用 count 屬性:
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("這字串有 \(unusualMenagerie.count) 個字元")
// 輸出 40
Swift 的
String 是基於 Unicode 標量 (Unicode Scalars) 建立的。這使得 Swift 對各種語言和特殊符號 (如 Emoji) 的支援非常好,但也意味著計算字串長度並不是單純的計算 byte 數量,因為某些字元可能由多個 Unicode 標量組成。比較字串
使用 == 來比較兩個字串的內容是否相同:
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("這兩個字串是一樣的")
}