How to compare two strings ignoring case in Swift language?

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

    localizedCaseInsensitiveContains : Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search

    if a.localizedCaseInsensitiveContains(b) {
        //returns true if a contains b (case insensitive)
    }
    

    Edited:

    caseInsensitiveCompare : Returns the result of invoking compare(_:options:) with NSCaseInsensitiveSearch as the only option.

    if a.caseInsensitiveCompare(b) == .orderedSame {
        //returns true if a equals b (case insensitive)
    }
    
    0 讨论(0)
  • 2020-12-13 06:09

    You can just write your String Extension for comparison in just a few line of code

    extension String {
    
        func compare(_ with : String)->Bool{
            return self.caseInsensitiveCompare(with) == .orderedSame
        } 
    }
    
    0 讨论(0)
  • 2020-12-13 06:10

    Swift 3: You can define your own operator, e.g. ~=.

    infix operator ~=
    
    func ~=(lhs: String, rhs: String) -> Bool {
       return lhs.caseInsensitiveCompare(rhs) == .orderedSame
    }
    

    Which you then can try in a playground

    let low = "hej"
    let up = "Hej"
    
    func test() {
        if low ~= up {
            print("same")
        } else {
            print("not same")
        }
    }
    
    test() // prints 'same'
    
    0 讨论(0)
  • 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<T>(_ 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
    
    0 讨论(0)
提交回复
热议问题