从“UIImage”下载? 到'UIImage'只解开optionals

我正在用图像创build一个UIButton

我写了下面的代码:

  let btnImg=UIButton.buttonWithType(UIButtonType.Custom) as UIButton let img = UIImage(named: "turn_left") as UIImage btnImg.setTitle("Turn left", forState: UIControlState.Normal) btnImg.setImage(img, forState: UIControlState.Normal) btnImg.frame = CGRectMake(10, 150, 200, 45) self.view.addSubview(btnImg) 

但是,我得到了以下错误let img = UIImage(named: "turn_left") as UIImage

 Swift Compiler error: Downcast from 'UIImage?' to 'UIImage' only unwraps optionals; did you mean to use '!'? 

作为错误说你必须使用'!' ,

试试下面的代码,

  let img = UIImage(named: "turn_left") as UIImage! // implicitly unwrapped 

要么

  let img : UIImage? = UIImage(named: "turn_left") //optional 

编辑

创buildimg你需要检查它为零之前使用它。

你总是可以在'if let'中做到这一点,但是根据swift的版本,注意语法上的差异。

Swift <2.0

 if let img = img as? UIImage { 

Swift 2.0

 if let img = img as UIImage! { 

注意感叹号的位置

如果UIImage初始化程序找不到指定的文件(或其他错误发生),它将返回nil ,根据苹果的文档

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

所以你需要把检查:

 let img = UIImage(named: "turn_left") if(img != nil) { // Do some stuff with it } 

您不需要将UIImage投射到UIImage ,这太浪费了。

编辑:完整的代码

 let img = UIImage(named: "turn_left") if(img != nil) { let btnImg = UIButton.buttonWithType(UIButtonType.Custom) as UIButton btnImg.setTitle("Turn left", forState: UIControlState.Normal) btnImg.setImage(img, forState: UIControlState.Normal) btnImg.frame = CGRectMake(10, 150, 200, 45) self.view.addSubview(btnImg) } 

您可能想要将elsebutton设置为一个形状或更有可能在“turn_left”不存在的情况下工作的其他东西。

由于UIImage(named:"something")返回一个可选项(因为如果方法没有find合适的图像,可能是nil,最好不要显式解开结果(否则你的app会崩溃),而是检查立即得到类似的东西:

  if let image = UIImage(named: "something"){ // now you can use image without ? because you are sure to have an image here! image.description } // continue your code here using the optional power of swift's vars! :) 

该方法如下:如果图像是可选的,则可以为空。 input一个可选的函数可以处理,否则他们通常会有意想不到的行为。 UIImage(named:) 可以返回零,你必须处理这个。 如果你明确地解开它,你可能会在稍后出现问题。

if let something = ... 东西将自动解包在运行时,你可以安全地使用它。