Swift3 - compare方法之ComparisonResult說明


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結果是相反的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM