Loading...

Different ways to compare strings in Swift

question swift
Ram Patra Published on November 17, 2023

Comparing two strings in Swift is straightforward and can be done using the equality operator ==. This operator checks if two strings are exactly the same in terms of their characters and the order in which these characters appear.

Here’s an example:

let string1 = "Hello"
let string2 = "World"
let string3 = "Hello"

let areStringsEqual1 = string1 == string2  // This will be false
let areStringsEqual2 = string1 == string3  // This will be true

In this example:

  • areStringsEqual1 evaluates to false because "Hello" and "World" are different strings.
  • areStringsEqual2 evaluates to true because both string1 and string3 are "Hello".

Case-Insensitive Comparison

If you want to compare strings in a case-insensitive manner (where “hello” is considered equal to “Hello”), you can use the lowercased() or uppercased() method on both strings before comparing:

let areStringsEqualCaseInsensitive = string1.lowercased() == string2.lowercased()

Locale-Sensitive Comparison

For locale-sensitive comparisons, where the comparison takes the user’s language and region settings into account (important in some languages), use localizedStandardCompare:

let comparisonResult = string1.localizedStandardCompare(string2) == .orderedSame

This method compares strings according to the rules of the current locale, which is typically the user’s locale.

Conclusion

String comparison in Swift is versatile and can be adapted to different needs, whether you require a simple equality check or a more complex, locale-aware comparison.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on November 17, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question macOS swift August 14, 2020 How to quit or close an app in macOS using Swift?

You can quit or exit an app with:NSApp.terminate(self)

question swift xcode October 8, 2023 How to get rid of 'Result of call to function is unused' warning in Swift/Xcode?

In Swift, if you encounter a “Result of call to ‘function’ is unused” warning, it means that you’re calling a function that returns a value (typically a result type, such as Result or any other type), but you’re not doing anything with the result. To get rid of this warning, you have a few options depending on the specific situation:

question swiftui swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.