NetDemo NetDemo - 2 years ago 79
Swift Question

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

I'm creating a

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)

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 Source

As error Says You have to use '!' ,

Try Below code,

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


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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download