0

Everyone knows you can use the == Operator to compare things.

if (stringValue1 == stringValue2)

If you do this in Objective-C the program will check if these objects are the same not if both strings do contain the same text. If you want to compare the text values you need to use a compare-Method.

To my understanding the same code in Swift does compare the text values. That is nice. A lot of programing language work like that. But what do I have to do to check if these two values refer to the same object?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
TalkingCode
  • 13,407
  • 27
  • 102
  • 147

2 Answers2

3

For objects of class type you can you the === operator to check whether two objects refer to the same instance. However, you ask specifically about strings. Strings in swift are not of class type - they are values. The === operator will not work for them - the same way as it does not work for integers. So the answer to your question - how to check if two strings are the same instance - in Swift is: it is not possible. With strings in Swift you should use normal operators like == etc. only.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
0

You can't as strings are values types, not object types. The === operator only works with object types (of AnyObject) but String is of type Any.

  6> "abc" === "abc"
repl.swift:6:1: error: type 'String' does not conform to protocol 'AnyObject'
"abc" === "abc"
^
Swift.lhs:1:5: note: in initialization of parameter 'lhs'
let lhs: AnyObject?
    ^

  6> var str : String = "abc"
str: String = "abc"
  7> str === str
repl.swift:7:1: error: type 'String' does not conform to protocol 'AnyObject'
str === str
^
Swift.lhs:1:5: note: in initialization of parameter 'lhs'
let lhs: AnyObject?
    ^
GoZoner
  • 67,920
  • 20
  • 95
  • 145