将强制向下转换为 'SCNView' 视为可选将永远不会产生 'nil'

问题描述

从 swift 4.2 开始,出现错误。在以前的版本中,代码运行良好(swift 3、4)。现在如何正确编写此代码swift4 swift4.2

class GameViewController: UIViewController {

var scene: SCNScene!
var scnView: SCNView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    setupScene()
    setupView()
}

func setupScene() {
    scene = SCNScene()
}

func setupView() {
    scnView = self.view as! SCNView
    scnView.scene = scene
}

}

解决方法

不要强制向下转换,而是使用可选的向下转换。 如果 self.view 不能转换为 SCNView,它将返回 nil

func setupView() {
  scnView = self.view as? SCNView
  scnView.scene = scene
}

你也可以这样处理失败:

func setupView() {
  if let scnView = self.view as? SCNView {
    scnView.scene = scene
  }
  else {
    // self.view couldn't be cast as SCNView,handle failure
  }
}
,

这似乎是 this bug 的一个实例,由您分配给的事物 scnView 引起,它是(隐式解包的)可选项,并且您正在使用 as!。这似乎是在暗示,由于您要分配给一个可选项,您可以只使用 as? 来代替它生成一个可选项,而不会崩溃。

假设您确定 self.view 是一个 SCNView(例如,因为您已将其设置在故事板中),并且您希望它在不知何故时快速失败不是 SCNView,您可以通过添加括号来消除警告:

scnView = (self.view as! SCNView)