How To Check If Two Strings Are Equal In Swift

By Eddy Chung

To check if two strings are equal in Swift you can use the == operator.

For example:

let string1 = "Hello World!"
let string2 = "Hello World!"
print(string1 == string2)
// true

Two string values are considered equal if they are canonically equivalent.

For most cases, that means if they look the same, they are equal.

There are a few exceptions but they are quite rare.

How To Check If Two Strings Are The Same Length In Swift

You can use the .count method to get the size of the string and then compare them:

var string1 = "Hello World!"
var string2 = "Happy World!"

print(string1.count == string2.count)
// true

How To Check If Two Strings Start With The Same String

You can use the prefix method to get the first part of any string to compare:

var string1 = "Hello World!"
var string2 = "Happy World!"

print(string1.prefix(1) == string2.prefix(1))
// true

In the above example, I compare the first character of both of the strings.

How To Check If Two Strings End With The Same String

You can use the suffix method to get the last part of any string to compare:

var string1 = "Hello World!"
var string2 = "Happy World!"

print(string1.suffix(6) == string2.suffix(6))
// true

In the above example, I compare the last 6 characters of both of the strings.

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts