Search code examples
iosswiftbinary-operatorsunichar

Using binary operator with unichar and String


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


Solution

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