-3

Swift Programming Language mentions using isEmpty to check for empty string. Are there cases where checking string against "" not yield the same result as using isEmpty?

In other words:

if str.isEmpty {
 XCTAssert(str == "", "This should be true as well")
}

From the documentation:

Find out whether a String value is empty by checking its Boolean isEmpty property:

if emptyString.isEmpty {
    print("Nothing to see here")
}
Boon
  • 40,656
  • 60
  • 209
  • 315
  • 3
    I don't understand what you mean, `"Will checking string with equality not do the same?"` Checking strings for equality determines whether or not they are equal. It does not say whether or not either is empty. You can only use an equality check to determine if a string is empty if you already know the other to be empty, but using `isEmpty` is probably better practice, if that's what you actually care about (it's more self-documenting). – nhgrif Nov 23 '15 at 14:00
  • 1
    Maybe the question is on what goes on under the hood? – Arc676 Nov 23 '15 at 14:07
  • @nhgrif Sorry for the confusion - rephrase question with example. – Boon Nov 23 '15 at 14:13
  • 1
    @Arc676 in which case, the only answer can be "who cares", because that will always be subject to change at Apple's will without notice. And as a general rule of programming, we should not be writing code around what's going on under the hood. – nhgrif Nov 23 '15 at 14:31

1 Answers1

5

The empty string is the only empty string, so there should be no cases where string.isEmpty() does not return the same value as string == "". They may do so in different amounts of time and memory, of course. Whether they use different amounts of time and memory is an implementation detail not described, but isEmpty is the preferred way to check in Swift (as documented).

Rob Napier
  • 286,113
  • 34
  • 456
  • 610