Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
strings
equals
case
communitycreator

Checking if two strings are equal by ignoring the case in Swift

Programming Bytes

We can use the caseInsensitiveCompare method to check if two strings are equal by ignoring the string case.

Syntax

func caseInsensitiveCompare(_ string: String) -> ComparisonResult

Parameter(s)

  • String: This is the string that needs to be compared with the current string.

Return type

This method returns ComparisonResult, which has:

  • ComparisonResult.orderedAscending: If the current string occurs before the argument string in lexical order.

  • ComparisonResult.orderedSame: If the current string and argument string are the same.

  • ComparisonResult.orderedDescending: If the current string occurs after the argument string in lexical order.

Code

The code given below shows us how to check if two strings are equal by ignoring the case:

import Swift

func compareStr(str1: String, str2: String ) -> Bool {
    return str1.caseInsensitiveCompare(str2) == .orderedSame
}

print(compareStr(str1: "test", str2:"TEST"));
print(compareStr(str1: "test", str2:"test"));
print(compareStr(str1: "test", str2:"best"));
Checking if two strings are equal by ignoring the case

Code explanation

  • Lines 3–5: We create a function with the name compareStr, which can take 2 string arguments and check whether or not the argument strings are equal by ignoring the case. Inside this method, we use the caseInsensitiveCompare method to see if it returns ComparisionResult.orderedSame. The method will return True if ComparisionResult.orderedSame is returned. Otherwise, it will return False.

  • Line 7: We call the compareStr method with the arguments 'test' and 'TEST'. Both the strings are the same, if we ignore the case sensitivity. Hence, True is returned.

  • Line 8: We call the compareStr method with the arguments 'test' and 'test'. Both the strings are the same, so True is returned.

  • Line 9: We call the compareStr method with the arguments 'test' and 'best'. Both the strings are different, so False is returned.

RELATED TAGS

swift
strings
equals
case
communitycreator
RELATED COURSES

View all Courses

Keep Exploring