Case Insensitive Comparison of Two Strings in Swift


In this Swift programming tutorial, you will learn how to compare two Swift strings with case insensitivity. That means we are going to ignore the case sensitivity of strings for this comparison.

For this case insensitive comparison of two Swift strings, we are going to use the caseInsensitiveCompare() method. The caseInsensitiveCompare() method is not part of the standard library. So we have to import the Foundation library to use it.

Below is the given code example where we are comparing two Swift strings with case insensitivity:

import Foundation

var siteSmall = "swiftspeedy"
var siteCapital = "SwiftSpeedy"
    
if(siteSmall.caseInsensitiveCompare(siteCapital) == .orderedSame){
    // This code block will run if the two strings are equal
}

Alternative method

We can also use the compare(_:options:) for the case insensitive comparison:

import Foundation

let site = "swiftspeedy"
let siteCapital = "SWIFTSPEEDY"

if site.compare(siteCapital, options: .caseInsensitive) == .orderedSame {
    // Execute this code block when the condition become true
}

There is another way you can do to compare the strings with case insensitivity by converting both of the strings two uppercase or lowercase. But it needs more code and is also not so friendly. So in this tutorial, I am not going to use this technique.


I have you have understood how we check if two strings are equal with case insensitive comparison.

Also read: