Binary operator '~=' cannot be applied to operands of type 'String' and 'String?'

Jurik picture Jurik · May 30, 2015 · Viewed 12.3k times · Source

I have a simple switch-statement that is not that simple.

switch(bubble?.name){ //bubble is SKPhysicsBody
    case "largeBubble": // <= error
        newBubbleSize = "medium"
        break;
    default:
        newBubbleSize = "large"
        break;
}

Here I get error that I mentioned in title Binary operator '~=' cannot be applied to operands of type 'String' and 'String?'. And I have no clue why it is a problem that one of them is an optional.

Answer

jtbandes picture jtbandes · May 30, 2015

Because of Optional Chaining, bubble?.name has type String?. You have a few options:

  • Use "largeBubble"? in your case expression (Swift 2+ only).
  • Check for nil before doing your switch, so the switch argument will be a String instead of String?.
  • Use bubble!.name (or bubble.name if it's a SKPhysicsBody!) if you are absolutely sure that it won't be nil