Reputation: 1866
I am seeing a strange issue. I am trying to compare 2 strings in Swift. One string is from the response I got from server. In the below code, it is printing as "Error" in outputString NSLog properly. But, when I do sting comparison in the next below line, it fails, it doesn't throw the error alert there. I don't know what i'm doing wrong here.
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
var outputString:NSString = NSString(data:data, encoding:NSUTF8StringEncoding)!
NSLog("outputString: %@", outputString)
if (outputString=="Error") {
NSLog("Error")
}
}
Upvotes: 1
Views: 2752
Reputation: 1057
I ran into a similar issue and the reason was a wrong encoding. I used UTF8 encoding, but the string I was comparing to was encoded with UTF16
String(data: model, encoding: .utf16) == String(data: data, encoding: .utf18)
is false
Upvotes: 3
Reputation: 6612
NSString
Class Reference : http://goo.gl/rPwMUxSwift Library Reference -
String
: http://goo.gl/591Ebo
The two are different. So you won't be able to apply certain operation on one or the other.
In order to compare two String
you can do outputString == "Error"
because the comparison operators exists.
However, in order to compare two NSString
you need to use the isEqualToString:
method. In your case, it should work like so : outputString.isEqualToString("Error")
.
Edit 1 :
Code examples here : http://swiftstub.com/445434073/
Edit 2 :
You can also compare String
with a NSString
with the ==
operator.
Upvotes: 1