Swift3在實現兩個對象比較時,引入了compare方法,其中,方法返回值ComparisonResult解釋如下:
ComparisonResult是一個枚舉類型,包含了以下3個成員:
其中:
q orderedAscending(-1):左操作數小於右操作數。
q orderedSame(0): 兩個操作數相等。
q orderedDescending(1):左操作數大於右操作數。
舉例:
func testCompare() { let str1 = "hello" let str2 = "world" print(str1.compare(str2).rawValue) let num1 = "1" let num2 = "2" print(num2.compare(num1).rawValue) let str11 = "hello" let str22 = "World" //compare區分大小寫 print(str11.compare(str22).rawValue) //compare不區分大小寫 設置options:caseInsensitive print(str11.compare(str22, options: .caseInsensitive, range: nil, locale: nil).rawValue) }
結果如下:
上面有個注意點,就是是否區分比較字符的大小寫
我們知道在ASCII碼中,小寫字母是排在大寫字母后面的。
所以: W < h < w
所以最后兩個print結果是相反的。