The binary operator '===' cannot be applied to two "String" operands

Why can't === be used with a string in Swift? I can not compile the following:

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

if string1 === string2 {
    ...
}

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

The binary operator '===' cannot be applied to two "String" operands


What I want to have in my unit tests is to execute copyWithZone: make sure that the two objects really represent another object with different pointers, even if their values ​​are the same. The following code does not work ...

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

If someone knows about an alternative method, please advise.

+4
source share
5 answers

string1 string2 NSString, String. , , ​​ ===.

+8

Swift === .

Swift String , . AnyObject .

, === String Swift, , == Swift String.

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

, , , , - :

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

== === :

XCTAssertEqual(foo, bar)
XCTAssertNotEqual(foo, bar)
+5

=== - . , . ( ), === .

, , .

Swift .

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

 XCTAssertFalse(object1 === object2)
+3
source

Swift Strings is a value type, not a reference type, so there is no need for this, the copy will always be another object.

You should just compare by value with ==.

+2
source

If you try very hard, you can make everything happen, but I'm not sure what you are buying.

class MyClass: NSObject, NSCopying {
    var someString: NSString = ""

    required override init() {
        super.init()
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        let copy = self.dynamicType.init()
        copy.someString = someString.copy() as? NSString ?? ""
        return copy
    }
}

let object1 = MyClass()
object1.someString = NSString(format: "%d", arc4random())
let object2 = object1.copy()

if object1.someString === object2.someString {
    print("identical")
} else {
    print("different")
}

prints identical, the system is really good at storing strings.

0
source

Source: https://habr.com/ru/post/1626187/


All Articles