How to compare two strings ignoring case in Swift language?

后端 未结 16 2615
孤街浪徒
孤街浪徒 2020-12-13 05:28

How can we compare two strings in swift ignoring case ? for eg :

var a = \"Cash\"
var b = \"cash\"

Is there any method that will return tru

16条回答
  •  误落风尘
    2020-12-13 05:55

    Try this:

    var a = "Cash"
    var b = "cash"
    let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
    
    // You can also ignore last two parameters(thanks 0x7fffffff)
    //let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)
    

    result is type of NSComparisonResult enum:

    enum NSComparisonResult : Int {
    
        case OrderedAscending
        case OrderedSame
        case OrderedDescending
    }
    

    So you can use if statement:

    if result == .OrderedSame {
        println("equal")
    } else {
        println("not equal")
    }
    

提交回复
热议问题