convenience init
So I learned a convenient and error-free way of assigning an image to an image view. Previously, I used a hardcoded string to access the image from the assets.
iv.imageView.image = UIImage(named: "someImage")
However, I thought of accessing images using the dot syntax. My objective was to achieve the following syntax.
iv.imageView.image = UIImage(named: .someImage)
The dot syntax is easy to use and human error-free. We don't need to use the hard-coded string explicitly, instead just use the dot to choose an image.
To achieve this, convenience init arrived as a saviour.
The convenience init is a special type of initializer in Swift that is used to create a convenience method to initialize an instance of a class or structure.
Here's what convenience init means and how it differs from a regular initializer:
In summary, a convenience init is a secondary initializer that provides a more convenient or alternative way to create an instance of a class or structure. It must call a designated initializer of the same class to ensure that all properties are properly initialized.
Recommended by LinkedIn
Here are a few steps one needs to take to choose the images using the dot syntax.
1) Creating an enum of type string that will hold the actual name of the image. The value is then mapped to its corresponding key.
For example
enum ImageName: String {
case message = "Message"
case lock = "Lock"
case appLogo = "AppLogo"
}{
2) After that, just extend the UIIMage and add the convenience init.
extension UIImage {
convenience init(named imageName: ImageName) {
self.init(named: imageName.rawValue)!
}
}
3) Now, Just access the images through dot syntax.
iv.imageView.image = UIImage(named: .message)
Thats all.