view raw
王怡飞 王怡飞 - 6 months ago 47
Swift Question

Swift how to compare string which come from NSString

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

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

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.


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.

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)
let str2 = "1"
if str1==str2 { println("same") }

Note a few other changes:

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

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)

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.