I am trying to make my code safer using Enums and a connivence initializer when dealing with UIImage and the Asset Catalog. My code is here below.
import UIKit
extension UIImage {
    enum AssetIdentifier: String {
        case Search = "Search"
        case Menu = "Menu"
    }
    convenience init(assetIdentifier: AssetIdentifier) {
        self.init(named: AssetIdentifier.RawValue)
    }
}
Currently I am getting this error.
'Cannot invoke 'UIImage.init' with an argument of type '(named: RawValue.Type)'
                There are 2 problems:
In your convenience initializer you are calling a failable initializer. So how can you guarantee that an instance of UIImage is always created when you are relying on a failable initializer that, by definition, does not guarantee that?
You can fix this by using the magic ! when you call the failable init.
When you call self.init you are not passing the param received in your init. You are instead referencing the enum definition. To fix this replace this
self.init(named: AssetIdentifier.RawValue)
with this
self.init(named: assetIdentifier.rawValue)
This is the result
extension UIImage {
    enum AssetIdentifier: String {
        case Search = "Search"
        case Menu = "Menu"
    }
    convenience init(assetIdentifier: AssetIdentifier) {
        self.init(named: assetIdentifier.rawValue)!
    }
}
UIImage(assetIdentifier: .Search)
                        You can use this code. I have tested it.
import UIKit
import Foundation
enum AssetIdentifier: String {
    case Search = "Search"
    case Menu = "Menu"
}
extension UIImage {
    convenience init?(assetIdentifier: AssetIdentifier) {
        self.init(named: assetIdentifier.rawValue)
    }
}
class ViewController: UIViewController {
    @IBOutlet var imageview: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imageview.image = UIImage(assetIdentifier: AssetIdentifier.Menu)
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With