非常短的版本:這不是一個斯威夫特高度的方法。通常有更好的工具。它主要用於ObjC。
import Foundation
let alice = "alice"
let bob = "bob"
let upBob = "BOB"
let bobby = "bobby"
// all are true
bob.compare(bob) == .orderedSame
bob.compare(alice) == .orderedDescending
bob.compare(upBob, options: .caseInsensitive) == .orderedSame
// This is a little weird in Swift because of how strings work. It's easier to use in ObjC
let rangeOfBob = bobby.range(of: "bob")!
bobby.compare(bob, range: rangeOfBob) == .orderedSame
bob.compare(umlaut, options: .diacriticInsensitive) == .orderedSame
關鍵的教訓是,compare
告訴你排序順序。如果兩個字符串相同,則獲得.orderedSame
。如果目標訂單在參數之前,那麼你得到.orderedAscending
。否則,.orderedDescending
。
compare
對於簡單的用法並不是很「快速」(您經常使用==
和<
代替)。但是,如果你需要類似變音不敏感的東西,它非常強大。對於不區分大小寫,您只需在Swift中使用lowercased(with:)
。
是的,但在Swift中很難使用。人們常常因爲不得不與'.orderedSame'進行比較而感到困惑。 –
它還允許您在兩個字符串如何被視爲「相等」的情況下提供更多選項。一個人爲的例子是Swift中的「resume!=résumé」,但如果你用'options:[.diacriticInsensitive]'調用函數,那麼它們是平等的。 'locale'參數是根據當地字母排序字符串。我不知道足夠的語言來考慮一個例子,當這會產生變化 –
同意'比較'更強大(見最後一段)。但在很多情況下,它並不是最Swifty的解決方案。 –