【问题标题】:Initializer for conditional binding must have Optional type, not 'UITouch'条件绑定的初始化程序必须具有 Optional 类型,而不是 'UITouch'
【发布时间】:2016-09-15 03:47:43
【问题描述】:

我目前在 SpriteKit 游戏的此代码块中遇到错误。在 if let 语句中,我收到以下错误。

条件绑定的初始化器必须是 Optional 类型,而不是 'UITouch'

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        StopSideMovement = false
        if let touch = touches.first! as UITouch {
            if touch.locationInView(self.view).x > screenWidth/2 {
                MoveRight = true
            } else if touch.locationInView(self.view).x < screenWidth/2 {
                MoveLeft = true
        }
    }
}

有人知道我该如何解决这个问题吗?谢谢!

【问题讨论】:

  • 是的,不要强制解包并仔细阅读 if let 语法 - 它需要一个可选的,但你没有给它一个可选的。
  • 只是一些与问题无关的注释。 1) 考虑到您的代码,如果触摸位置正好是screenWidth/2,则永远不会发生。这样对吗? 2) 您正在使用 2 个布尔变量 MoveLeftMoveRight。将var direction: Direction?Direction 声明为enum Direction { case Left, Right } 之类的东西会不会更容易?
  • 请检查我们提供的答案。

标签: ios swift sprite-kit


【解决方案1】:

这一行

if let touch = touches.first! as UITouch {

应该是

if let touch = touches.first {

为什么?

touches.first 确实返回 UITouch?。但是如果你添加这个人! 并写

touches.first!

然后您正在执行强制解包,并且您(在编译时)获得UITouch

因此不再需要整个条件展开。

当然,您应该避免使用force unwrap 使用更安全的语句(如conditional unwrapping),除非您绝对确定 Optional 中会有一些价值。

【讨论】:

    【解决方案2】:

    Set 内容的类型指定为UITouch。所以你不需要沮丧。你只需要打开它。

    if let touch =  touches.first {}
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2021-04-26
      • 2016-01-27
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多