How do you verify the identity of strings in Swift?

Swift, like several other languages, has an identity operator ===

. But it looks like you cannot use it against strings:

var x = "hello"
var y = "hello"
if x === y {         //ERROR: 'String' does not conform to protocol 'AnyObject'
    println("SAME!")
}else {
    println("DIFFERENT!")
}

      

Isn't there a direct method for testing string identity?! ... or am I missing something?

+3


source to share


1 answer


Strings in Swift are value types, not reference types. That is, they have value, not identity. In this sense, it makes no sense to check if two strings have the same "identity". If they are not the same variable, they are different. Instead, you should just check if they have the same meaning with ==

.

There might be internment under the hood. In fact, there is definitely:

struct StringBits {
    let underlyingPtr: UnsafeMutablePointer<Void>
    let padding1: UnsafeMutablePointer<Void>
    let padding2: UnsafeMutablePointer<Void>
}

let s1 = "abcd"
let s2 = "abcd"

let bits1 = unsafeBitCast(s1, StringBits.self)
let bits2 = unsafeBitCast(s2, StringBits.self)

println(bits1.underlyingPtr) //      0x0000000117654000
println(bits2.underlyingPtr) // also 0x0000000117654000

      

Likewise, if you initialize one string from another, they will share the same memory until one of them is mutated (i.e., the strings are copied for writing).



But these details are hidden from you as implementation details that you are supposed to know. As for semantics, then s1

, and s2

not fully connected.

If you're interested in performance, the underlying String type will probably use pointers to its storage to effectively check for equality in cases where they are using the same storage. Arrays (which are implemented similarly), as you can see here:

struct NeverEqual: Equatable { }

// NOT a correct implementation of ==, since == must be
// reflexive, and this isn’t:
func ==(lhs: NeverEqual, rhs: NeverEqual)->Bool { return false }

let x=[NeverEqual()]
let y=x

// this returns true – because it doesn’t bother comparing the 
// elements, because it knows x and y share the same storage
x==y

      

+4


source







All Articles