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

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


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.


You can always do it in an 'if let' but note the difference in syntax depending on the version of swift.

Swift < 2.0:

if let img = img as? UIImage {

Swift 2.0:

if let img = img as UIImage! {

Note the position of the exclamation


If the UIImage initialiser cannot find the file specified (or some other error happened), it will return nil, as per Apple's documentation

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

So you need to put checks in:

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

You don't need to cast a UIImage to a UIImage, that's a waste.

Edit: Full code

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)}

You may want to put an else in to set the button to a shape or something else that is more likely to work in the case "turn_left" doesn't exist.