1

I'm trying to return a value (string) from php to IOS application:

echo "1";

This is the swift code:

let returnedData = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue) as! String
print(returnedData)
if returnedData == "1" {
     ... something
}

The print function shows the correct value (that is, 1). But the check fails.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Fab
  • 1,145
  • 7
  • 20
  • 40

1 Answers1

0

String(...) gives me Optional("1\n\n")

That indicates that the output is followed by two newline characters, as in this example:

let data = Data(bytes: [0x31, 0x0a, 0x0a])
if let string = String(data: data, encoding: .utf8) {
    print(string) // 1
    print(string.debugDescription) // "1\n\n"
    print(string == "1") // false
}

debugDescription is a very useful method to detect “invisible” string characters.

The solution is (compare Does swift have a trim method on String?):

let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmed == "1") // true
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382