任何人都可以用示例解释string.compare(_:options:range:locale :)吗?

时间:2017-05-26 13:28:16

标签: swift swift3

任何人都可以在实际例子中解释下面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

1 个答案:

答案 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:)