Skip to content

Instantly share code, notes, and snippets.

@JARinteractive
Last active October 30, 2019 21:29
Show Gist options
  • Save JARinteractive/9a37e9cef90d9d3d912430c5a54eb727 to your computer and use it in GitHub Desktop.
Save JARinteractive/9a37e9cef90d9d3d912430c5a54eb727 to your computer and use it in GitHub Desktop.
Image Enum

Safer Image/Resource Loading

  • non-optional UIImages
  • convenience API to build UIImageViews with static resources
  • easy to load images from within a framework
  • test verifies that all images exist, preventing accidental removal
  • this approach could easily be adapted to other types of resources
import UIKit
public enum Image: String {
private static let bundle = Bundle(for: ClassInImageBundle.self)
// Your images here:
case imageOne = "image-1"
case imageTwo = "image-2"
public var uiImage: UIImage {
return UIImage(named: rawValue, in: Bundle.jmKit, compatibleWith: nil) ?? UIImage()
}
public var cgImage: CGImage {
return uiImage.cgImage ?? UIImage().cgImage!
}
public var size: CGSize {
return uiImage.size
}
public var imageView: UIImageView {
return UIImageView(image: uiImage)
}
}
private class ClassInImageBundle: NSObject {}
import XCTest
import <AppOrFramework>
class ImageTest: XCTestCase {
func testImagesExist() {
Image.allCases.forEach { image in
XCTAssertTrue(verifyImage(image))
}
}
private func verifyImage(_ image: Image) -> Bool {
return image.uiImage.size != CGSize.zero
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment