Search code examples
iosswiftenumsswift2init

Swift UIImage extension


I am trying to make my code safer using an enum and a convenience initializer when dealing with UIImage and the asset catalog. My code is 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)'


Solution

  • There are 2 problems:

    1. Failable init

    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.

    2. Referencing the param you received

    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)
    

    Wrap up

    This is the result

    extension UIImage {
        enum AssetIdentifier: String {
            case Search = "Search"
            case Menu = "Menu"
        }
        convenience init(assetIdentifier: AssetIdentifier) {
            self.init(named: assetIdentifier.rawValue)!
        }
    }
    

    Testing

    UIImage(assetIdentifier: .Search)