Swift 的 String 直接支援各種比較運算子,寫起來比 Objective-C 直覺許多。除了相等判斷,還能比大小、檢查前綴後綴、轉換大小寫,以及嘗試轉型成數字。
==、!=、<、>、<=、>= 全部都能用在字串上,字串會依字典序逐字元比較。
let str = "hello"
if str == "hello" {
print(str)
}
if str < "heoo" {
print(str)
}hasPrefix 與 hasSuffix 是處理路徑、副檔名、網址時的常用工具。
let str1 = "apple"
// 判斷是否含有前綴
if str1.hasPrefix("ap") {
print(str1)
}
// 判斷是否含有後綴
if str1.hasSuffix("le") {
print(str1)
}uppercased() 與 lowercased() 都會回傳一個新的字串,不會改動原本的值。
let str2 = str1.uppercased() // "APPLE" let str3 = str2.lowercased() // "apple" print(str2) print(str3)
早期 Swift 有 toInt() 這個方法,現在已改為使用 Int() 初始化器。轉換失敗時會得到 nil,所以結果是 optional,必須先判斷再解包。
let str4 = "255d"
// 舊寫法已不適用:let d:Int? = str4.toInt()
let d1: Int? = Int(str4)
print("-------->")
print(d1) // 內容不是合法整數,印出 nil如果對 optional 直接強制解包(Int(str4)!),在字串無法轉型的情況下會造成 runtime 崩潰,因此養成先用 if let 綁定的習慣會安全得多。