2

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

zaph
  • 111,848
  • 21
  • 189
  • 228
Pete
  • 613
  • 1
  • 6
  • 18

2 Answers2

8

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   
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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"

vacawama
  • 150,663
  • 30
  • 266
  • 294