任何人都可以在实际例子中解释下面String
函数的用法是什么。
func compare(_ aString: String, options mask: String.CompareOptions = default, range: Range<String.Index>? = default, locale: Locale? = default) -> ComparisonResult
https://developer.apple.com/reference/swift/string/1412785-compare
答案 0 :(得分:1)
非常短的版本:这不是Swift中高度使用的方法。通常有更好的工具。它主要用于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
不是很快&#34; Swifty&#34;简单使用(您经常使用==
和<
)。但如果你需要像变音不敏感这样的东西,它会非常强大。对于不区分大小写的情况,您只需在Swift中使用lowercased(with:)
。