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.
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
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.
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.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.