[英]Binary operator '~=' cannot be applied to operands of type 'String' and 'String?'
I have a simple switch-statement that is not that simple. 我有一个简单的switch语句并不那么简单。
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?'
这里我得到错误,我在标题中提到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?
由于可选链接 , bubble?.name
类型为String?
. 。 You have a few options: 你有几个选择:
"largeBubble"?
使用"largeBubble"?
in your case
expression (Swift 2+ only). 在你的case
表达式中(仅限Swift 2+)。 switch
, so the switch argument will be a String
instead of String?
在进行switch
之前检查nil,因此switch参数将是String
而不是String?
. 。 bubble!.name
(or bubble.name
if it's a SKPhysicsBody!
) if you are absolutely sure that it won't be nil 如果你绝对肯定它不会是零,请使用bubble!.name
(或bubble.name
如果它是SKPhysicsBody!
) As @jtbandes said, the problem is the result of bubble?.name
having type String?
正如@jtbandes所说,问题是bubble?.name
的结果bubble?.name
有String?
类型String?
. 。 An alternative solution, to the ones given, is to override the ~=
operator to take a String?
对于给定的解决方案,另一种解决方案是覆盖~=
运算符以获取String?
and String
as arguments, for example: 和String
作为参数,例如:
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 这里的width是一个Integer类型,它已被String(Int)函数转换为String
In Swift 2.0 (sender: UIButton) then ! 在Swift 2.0(发件人:UIButton)然后! for the switch string works. 对于开关串工作。
let operation = sender.currentTitle!
In Swift 2.0, (sender: AnyObject ) then !! 在Swift 2.0中,(发送者: AnyObject )然后!! for the switch string works. 对于开关串工作。
let operation = sender.currentTitle!!
the mistake which i made is using AnyObject instead of UIButton. 我犯的错误是使用AnyObject而不是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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.