Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Swift equivalent of isEqualToString in Objective-C?

Tags:

string

swift

People also ask

Can you compare strings in Swift?

In Swift, you can check for string and character equality with the "equal to" operator ( == ) and "not equal to" operator ( != ).

How do you check if two strings are the same in Swift?

To check if two strings are equal in Swift, use equal to operator == with the two strings as operands. The equal to operator returns true if both the strings are equal or false if the strings are not equal.

What is not equal to in Swift?

Swift supports the following comparison operators: Equal to ( a == b ) Not equal to ( a !=

How do I get the length of a string in Swift?

Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.


With Swift you don't need anymore to check the equality with isEqualToString

You can now use ==

Example:

let x = "hello"
let y = "hello"
let isEqual = (x == y)

now isEqual is true.


Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).


I addition to @JJSaccolo answer, you can create custom equals method as new String extension like:

extension String {
     func isEqualToString(find: String) -> Bool {
        return String(format: self) == find
    }
}

And usage:

let a = "abc"
let b = "abc"

if a.isEqualToString(b) {
     println("Equals")
}

For sure original operator == might be better (works like in Javascript) but for me isEqual method gives some code clearness that we compare Strings

Hope it will help to someone,


In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}