Easier interaction between UIImage and assets

Roland Leth
1 min readJun 11, 2016

--

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

// A bang isn'tthat 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)

Originally published at rolandleth.com.

--

--

Roland Leth
Roland Leth

Written by Roland Leth

iOS & web developer. Blogger about life and tech at https://rolandleth.com. Founder at https://runtimesharks.com.

No responses yet