swiftswift-optionals

how can i fix this? it tells me that optional "!" is not needed


var camera = UIImage(named: "1")! 
var city = UIImage(named: "2")! 
var animals = UIImage(named: "3")! 
var flowers = UIImage(named: "4")! 
var stand = UIImage(named: "5")! 
var urban = UIImage(named: "6")!

it seems normal until i run the project.


Solution

  • Declare images like

    let camera: UIImage = UIImage(named: "1") ?? UIImage()
    

    and then you will be sure that even when there is no image named "1" the app won't crash.

    You can also create UIImage extension

    extension UIImage {
    
        static let camera: UIImage = UIImage(named: "1") ?? UIImage()
    
    }
    

    and use images like that:

    yourImageView.image = .camera