Swift – Check if Strings are Equal
To check whether two strings are equal in Swift, use the equal-to operator ==. It compares the values of the two String operands and returns true when they are equal; otherwise, it returns false.
Swift string comparison is case-sensitive by default. Therefore, "Swift" and "swift" are not equal. Spaces, punctuation, and other characters also take part in the comparison.
Swift String Equality Syntax
The syntax for comparing two Swift strings is:
str1 == str2
You can use the expression directly in an if condition, assign its Boolean result to a variable, or print the result.
Compare Two Equal Strings in Swift
In the following example, str1 and str2 contain the same sequence of characters. The == expression evaluates to true, so the first message is printed.
main.swift
var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial in TutorialKart"
// compare if the strings are equal
if str1 == str2 {
print("str1 and str2 are equal")
} else {
print("str1 and str2 are not equal")
}
Output
$swift strings_equal.swift
str1 and str2 are equal
Compare Two Different Strings in Swift
In this example, the strings have different values. The equality check returns false, and the else block runs.
main.swift
var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial"
// compare if the strings are equal
if str1 == str2 {
print("str1 and str2 are equal")
} else {
print("str1 and str2 are not equal")
}
Output
$swift strings_equal.swift
str1 and str2 are not equal
Print the Boolean Result of Swift String Comparison
The equality expression itself produces a Boolean value. The following program prints the result of two string comparisons.
main.swift
var str1 = "Swift Tutorial in TutorialKart"
var str2 = "Swift Tutorial"
var str3 = "Swift Tutorial"
print("str1 == str2 : \(str1==str2)")
print("str2 == str3 : \(str2==str3)")
Output
$swift strings_equal.swift
str1==str2 : false
str2==str3 : true
Check Whether Swift Strings Are Not Equal
Use the not-equal operator != when the condition should be true only when the two strings have different values.
str1 != str2
let expectedRole = "Admin"
let currentRole = "Editor"
if currentRole != expectedRole {
print("The roles are different")
}
The roles are different
Case-Sensitive String Equality in Swift
The == operator performs a case-sensitive comparison. Letter case must match for the strings to be equal.
let first = "Swift"
let second = "swift"
print(first == second)
false
Case-Insensitive String Comparison in Swift
For a case-insensitive comparison, import Foundation and use compare(_:options:) with the .caseInsensitive option. The strings are equal when the result is .orderedSame.
import Foundation
let first = "Swift"
let second = "swift"
let areEqualIgnoringCase =
first.compare(second, options: .caseInsensitive) == .orderedSame
print(areEqualIgnoringCase)
true
Calling lowercased() on both strings can be sufficient for simple, non-localized identifiers, but Foundation comparison options are clearer when the intended rule is case-insensitive text comparison.
Compare Swift Strings After Removing Extra Whitespace
User input may contain leading or trailing spaces. Normalize the values before comparing them when surrounding whitespace should not affect equality.
import Foundation
let enteredName = " Taylor "
let savedName = "Taylor"
let normalizedEnteredName =
enteredName.trimmingCharacters(in: .whitespacesAndNewlines)
print(normalizedEnteredName == savedName)
true
Swift String Value Equality Versus Object Identity
Use == for Swift String values. Unlike Objective-C object comparisons, Swift strings do not require an isEqualToString method. The identity operator === is for checking whether two class references point to the same instance; it is not used for String, which is a value type.
Unicode Behavior in Swift String Equality
Swift strings use Unicode-aware value comparison. Canonically equivalent representations of the same character can compare as equal, such as a precomposed accented character and the corresponding base character followed by a combining mark. Compatibility characters, such as some ligatures and presentation forms, should not be assumed to compare as equal unless you normalize them according to the rules required by your application.
Common Mistakes When Comparing Strings in Swift
- Using
===instead of==for string values. - Expecting
"Swift"and"swift"to be equal without a case-insensitive comparison. - Ignoring leading spaces, trailing spaces, or newline characters in user input.
- Comparing an optional
String?without first deciding hownilshould be handled. - Using locale-sensitive text rules for identifiers, tokens, file extensions, or protocol values where exact matching is required.
Swift String Equality FAQs
How do I check if two strings are equal in Swift?
Use string1 == string2. The expression returns true when the two string values are equal and false otherwise.
Is Swift string comparison case-sensitive?
Yes. The == operator is case-sensitive, so "HELLO" and "hello" are different values.
How can I compare Swift strings without considering case?
Import Foundation and check whether first.compare(second, options: .caseInsensitive) returns .orderedSame.
What is the Swift equivalent of Objective-C isEqualToString?
For Swift String values, use the == operator. It compares the string values directly.
Can I compare optional strings with the == operator?
Yes. Two optional strings can be compared when both sides have compatible optional types. Two nil values compare as equal, while nil and a non-nil string do not. In application code, make the intended handling of missing values explicit.
Editorial QA Checklist for Swift String Comparison
- Confirm that examples use
==for value equality and!=for inequality. - Verify that case-sensitive and case-insensitive comparisons are described separately.
- Check that Foundation is imported in examples using
compare(_:options:)or whitespace trimming. - Ensure output blocks match the comparison results shown in the Swift code.
- Retain the distinction between Unicode canonical equivalence and compatibility normalization.
Summary of Swift String Equality
Use == to check whether two Swift strings have equal values and != to check whether they differ. The default comparison is case-sensitive. For case-insensitive user-facing text, use an appropriate Foundation comparison option, and normalize whitespace or other input variations only when the application requires it.
In this Swift Tutorial, we have learned to check if two strings are equal with the help of Swift program examples.
TutorialKart.com