Downcast from 'UIImage?' to 'UIImage' only unwraps optionals
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.