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

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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stoikokolev