二进制运算符'〜='不能应用于'String'和'String?'类型的操作数

Jur*_*rik 7 switch-statement skphysicsbody swift

我有一个简单的switch语句并不那么简单.

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

在这里,我得到了我在标题中提到的错误Binary operator '~=' cannot be applied to operands of type 'String' and 'String?'.我不知道为什么其中一个是可选的问题.

jtb*_*des 8

因为可选链接,bubble?.name有类型String?.你有几个选择:

  • "largeBubble"?case表达式中使用(仅限Swift 2+).
  • 在做之前检查nil switch,因此switch参数将是a String而不是String?.
  • 使用bubble!.name(或bubble.name如果是a SKPhysicsBody!)如果你绝对确定它不会是零