Case Insensitive Comparison of Strings in Swift

In this short Swift code example, you will learn how to compare two strings despite their case sensitivity. To do that we will use the caseInsensitiveCompare() function and the ComparisonResult enumeration.

Using caseInsensitiveCompare() and ComparisonResult

let valueExpected = "SUCCESS"
let valueProvided = "success"

if valueExpected.caseInsensitiveCompare(valueProvided) == ComparisonResult.orderedSame
{
    print("Strings are equal")
}

In the code example above, the caseInsensitiveCompare returns a ComparisonResult value that indicates the lexical ordering. The ComparisonResult indicates how items in a request are ordered, from the first one given in a method invocation or function call to the last (that is, left to right in code).

ComparisonResult is an Enum that has a few options:

  • ComparisonResult.orderedAscending  –  the left operand is smaller than the right operand.
  • ComparisonResult.orderedSame  – where the two operands are equal, and
  • ComparisonResult.orderedDescending – where the left operand is greater than the right operand.

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.