Swift如何比较来自NSString的字符串 [英] Swift how to compare string which come from NSString

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

问题描述

我得到一个返回数字(0代表成功,1代表失败)form server由php
所以我想得到这个数字来判断我的操作是否成功。
我使用这个:

I get a return number(0 for success, 1 for failure) form sever made by php so I want get this number to judge my operation succeeded or not. I use this :

var str1 :String = NSString(data: d, encoding: NSUTF8StringEncoding)!
let str2 = "1"
println(str1) // output is 1
println(str2) // output is 1

if(str1==str2){println("same")} //but the two is not same

这和我得到这个结果:
// str1 _countAndFlags UWord 13835058055282163717 -4611686018427387899
// str2 _countAndFlags UWord 1 1

so I debug for this and I get this result: //str1 _countAndFlags UWord 13835058055282163717 -4611686018427387899 //str2 _countAndFlags UWord 1 1

toInt。我得到1383 ...形式str3和1形式str4
那么我该如何解决这个问题。
非常感谢。

And I try to use toInt. I get 1383... form str3 and 1 form str4 So how can I do to solve this problem. Thank you very much.

推荐答案

听起来你的字符串中有一些空格。要使用 println 找到这个,你可以尝试 println(,。join(map(str1,toString)))。如果你看到任何逗号,这是问题。

It sounds like you have some whitespace in your string. To spot this using println, you could try println(",".join(map(str1,toString))). If you see any commas at all, that's the problem.

解决这个问题最简单的方法是(可能更好的杀死空间的来源)是使用 stringByTrimmingCharactersInSet

The easiest way to fix this (it may be better to kill the whitespace at the source) is to use stringByTrimmingCharactersInSet:

let str1: String = NSString(data: d, encoding: NSUTF8StringEncoding)
                   ?.stringByTrimmingCharactersInSet(
                     NSCharacterSet.whitespaceAndNewlineCharacterSet())
let str2 = "1"
if str1==str2 { println("same") }

请注意一些其他更改:


  • 而不是 var ,因为它看起来不像你需要更改<$ c $

  • 在创建结束时没有强制解开()的 NSString 。不要强制解开可能为nil的东西,你会得到一个运行时错误!

  • ?。不是零。

  • let rather than var since it doesn't look like you need to change str1 after it's declared
  • No force-unwrap (!) at the end of the creation of the NSString. Never force-unwrap something that might be nil, you will get a runtime error!
  • ?. to optionally call the trim if it isn't nil.

注意,这意味着 str1 是一个 String ?不是 String ,但是很好,因为你可以比较可选项和非可选项(如果可选项包含等于非可选的,但不是如果可选的包含 nil

Note, this means str1 is a String? not a String but that's fine since you can compare optionals with non-optionals (they'll be equal if the optional contains a value equal to the non-optional, but not if the optional contains nil)

如果你真正想要的是一个 Int ,只需添加一个 let int1 = str1?.toInt()。这仍然是可选的 - 如果在 nil 的情况下有合理的默认值,你可以做 let int1 = str1?.toInt()? ? 0 ,在 nil 的情况下为 0

If what you actually want is an Int, just add a let int1 = str1?.toInt(). This will still be an optional – if there is a reasonable default in case of nil, you could do let int1 = str1?.toInt() ?? 0 and it will be non-optional with a value of 0 in case of nil.

这篇关于Swift如何比较来自NSString的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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