在Swift中比较2个字符串失败 [英] Comparing 2 strings fails in Swift

查看:42
本文介绍了在Swift中比较2个字符串失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个奇怪的问题.我正在尝试比较Swift中的2个字符串.一个字符串来自我从服务器获得的响应.在下面的代码中,它在outputString NSLog中正确打印为错误".但是,当我在下面的下一行进行比较时,它失败了,并且没有在此处引发错误警报.我不知道我在做什么错.

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")
    }
}

推荐答案

NSString 类参考: http://goo.gl/rPwMUx

Swift库参考- String : http://goo.gl/591Ebo

Swift 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.

为了比较两个 String ,您可以执行 outputString =="Error" ,因为存在比较运算符.

In order to compare two String you can do outputString == "Error" because the comparison operators exists.

但是,为了比较两个 NSString ,您需要使用 isEqualToString:方法.在您的情况下,它应该像这样工作: outputString.isEqualToString("Error")).

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").

此处的代码示例: http://swiftstub.com/445434073/

您还可以将 String 与带有 == 运算符的 NSString 进行比较.

You can also compare String with a NSString with the == operator.

这篇关于在Swift中比较2个字符串失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆