How to compare two strings ignoring case in Swift language?

后端 未结 16 2588
孤街浪徒
孤街浪徒 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 06:11

    Swift 4, I went the String extension route using caseInsensitiveCompare() as a template (but allowing the operand to be an optional). Here's the playground I used to put it together (new to Swift so feedback more than welcome).

    import UIKit
    
    extension String {
        func caseInsensitiveEquals(_ otherString: T?) -> Bool where T : StringProtocol {
            guard let otherString = otherString else {
                return false
            }
            return self.caseInsensitiveCompare(otherString) == ComparisonResult.orderedSame
        }
    }
    
    "string 1".caseInsensitiveEquals("string 2") // false
    
    "thingy".caseInsensitiveEquals("thingy") // true
    
    let nilString1: String? = nil
    "woohoo".caseInsensitiveEquals(nilString1) // false
    

提交回复
热议问题