Jurik
Jurik

Reputation: 3264

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

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.

Upvotes: 7

Views: 12605

Answers (4)

Ranjithkumar
Ranjithkumar

Reputation: 707

In Swift 2.0 (sender: UIButton) then ! for the switch string works.

let operation = sender.currentTitle!

In Swift 2.0, (sender: AnyObject) then !! for the switch string works.

let operation = sender.currentTitle!!

the mistake which i made is using AnyObject instead of UIButton.

@IBAction func operate(sender: AnyObject) {
        let operation = sender.currentTitle!!

        if userIsInTheMiddleOfTypeingNumber{
            enter()
        }

        switch operation{
            case "×":
                if operandStack.count >= 2{
                    displayValue = operandStack.removeLast() * operandStack.removeLast()
                }

                break
//            case "÷":
//                break
//            case "+":
//                break
//            case "−":
//                break
           default:
                break
        }

    }

Upvotes: 0

Pias
Pias

Reputation: 218

“Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.”

“let label = "The width is "
let width = 94
let widthLabel = label + String(width)”

Here width is an Integer type it has been converted to String by String(Int) function

Upvotes: 1

jtbandes
jtbandes

Reputation: 118711

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

Upvotes: 8

ABakerSmith
ABakerSmith

Reputation: 22939

As @jtbandes said, the problem is the result of bubble?.name having type String?. An alternative solution, to the ones given, is to override the ~= operator to take a String? and String as arguments, for example:

func ~= (lhs: String, rhs: String?) -> Bool {
    return lhs == rhs
}

Or, to make it more generic:

func ~= <T: Equatable>(lhs: T, rhs: T?) -> Bool {
    return lhs == rhs
}

Upvotes: 3

Related Questions