Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operator '===' cannot be applied to two 'String' operands

Tags:

swift

Why can't the === be used with String's in Swift? I am unable to compile the following:

let string1 = "Bob"
let string2 = "Fred"

if string1 === string2 {
    ...
}

and get the following error (on the if line):

Binary operator '===' cannot be applied to two 'String' operands


What I want to be able to do in my unit tests is, having performed a copyWithZone:, verify that two objects are indeed a different object with different pointers even if their values are the same. The following code doesn't work...

XCTAssertFalse(object1.someString === object2.someString)

If anyone knows of an alternative way please advise.

like image 815
Oliver Pearmain Avatar asked Jan 27 '16 13:01

Oliver Pearmain


3 Answers

string1 and string2 are not NSString, but String. Since they are value objects, not reference objects, there is no reference that could be compared with ===.

like image 188
gnasher729 Avatar answered Nov 20 '22 08:11

gnasher729


Swift's === operator, by default, is only defined for classes.

Swift's String type is not a class but a struct. It does not inherit from AnyObject and therefore cannot be compared by reference.

You could of course implement an === operator for String in Swift, but I'm not sure how it would be any different from the implementation of == for Swift's String type.

func ===(lhs: String, rhs: String) -> Bool {
    return lhs == rhs
}

Unless, of course, you really wanted to compare the references, I suppose you could do something like this:

func ===(lhs: String, rhs: String) -> Bool {
    return unsafeAddressOf(lhs) == unsafeAddressOf(rhs)
}

However, for the sake of tests, rather than using the == or === operators, you should use the appropriate assertions:

XCTAssertEqual(foo, bar)
XCTAssertNotEqual(foo, bar)
like image 27
nhgrif Avatar answered Nov 20 '22 09:11

nhgrif


The === operator is the identity operator. It checks if two variables or constants refer to the same instance of a class. Strings are not classes (they are structs) so the === operator does not apply to them.

If you want to check if two strings are the same, use the equality operator == instead.

Read all about the identity operator in the Swift documentation.

You can just check two objects for identity directly, instead of checking a property of type String.

 XCTAssertFalse(object1 === object2)
like image 3
Marc Khadpe Avatar answered Nov 20 '22 08:11

Marc Khadpe