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.
Because of Optional Chaining, bubble?.name
has type String?
. You have a few options:
"largeBubble"?
in your case
expression (Swift 2+ only).switch
, so the switch argument will be a String
instead of String?
.bubble!.name
(or bubble.name
if it's a SKPhysicsBody!
) if you are absolutely sure that it won't be nilAs @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
}
“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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With