可选类型 'UIImage?' 的值未展开;你是不是想用'!'要么 '?'?插入 '!'

Value of optional type 'UIImage?' not unwrapped; did you mean to use '!' or '?'? Insert '!'

当我为视图控制器设置背景图像时,出现了这样的错误....

Error:    Value of optional type 'UIImage?' not unwrapped; did you mean to use '!' or '?'? Insert '!'

我的代码是...

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "image.png"))

}

修复:

let image = UIImage(named: "image.png")
if image != nil {
    self.view.backgroundColor = UIColor(patternImage:image)
}

因为UIImage(named: "image.png"),这将return可选图像对象。即如果图像无效,它将 return nil。

From Apple docs

Return 值

The image object for the specified file, or nil if the method could not find the specified image.

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "image.png"))替换为self.view.backgroundColor = UIColor(patternImage: UIImage(named: "image.png")!)