:  ~ 1 min read

Easier interaction between UIImage and assets

We all hate explicitly typed strings, especially for creating UIImages, but we can surely improve on that. Let's start with an enum, that has a var, to transform its raw value into an UIImage:

enum Asset: String {
  case back = "leftArrow"
  case logo
  case email
  case briefcase
	
  // Theoretically, a bang wouldn't be that bad here, 
  // as we should be 100% sure of what goes in this enum
  var image: UIImage? {
    return UIImage(named: rawValue)
  }
}

And why not improve UIImageView too, while we're at it?

extension UIImageView {
  convenience init(asset: Asset) {
    self.init(image: asset.image)
  }
}

Now, by having autocomplete, our calls are easier, and safer:

let backImage = Asset.back.image
let emailImage = Asset.logo.image

let logoImageView = UIImageView(asset: .logo)
let briefcaseImageView = UIImageView(asset: .briefcase)