NetDemo NetDemo - 6 months ago 13
Swift Question

Downcast from 'UIImage?' to 'UIImage' only unwraps optionals

I'm creating a

UIButton
with an image,

I have written the below code for that:

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)


But I got the error below at
let img = UIImage(named: "turn_left") as UIImage
:

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

Answer

As error Says You have to use '!' ,

Try Below code,

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

OR

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

Edit

After creating img you need to check it for nil before using it.

Comments