Using binary operator with unichar and String

1.7k views Asked by At

I am attempting to use a binary operator to compare two values:

character = (xxx as NSString).characterAtIndex(2)
if character == "1" {
    //do this thingy   
}

Now I receive the failure message Binary Operator '==' cannot be applied to operands of type unichar or String. I have also attempted to convert the character:

if String(character) == "1" 

Does not work...

2

There are 2 answers

0
Sergey Kalinichenko On BEST ANSWER

Since unichar is a type aliased to a 16-bit integer, you need to "wrap" it in UnicodeScalar function for the comparison:

if UnicodeScalar(character) == "1" {
    //do this thingy   
}
0
vacawama On

Here's another approach. Change the way you are getting character from the String:

let xxx = "321"
let character = xxx[advance(xxx.startIndex, 2)]
if (character == "1") {
    println("it is a 1")
}

output:

"it is a 1"