How To Check If Two Strings Are Equal In Swift

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 and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts