ImageSource

public class ImageSource : Equatable

A general class to represent an image that may require some work to create or load. You create an ImageSource by passing to the initializer a generating function, a closure that returns the UIImage of interest.

The generation function may do any work necessary to create the UIImage object, and the ImageSource image property is lazy initialized with the value returned from the generator the first time it is accessed.

The use case for URL images is thus the following:

   let url = URL(...)
   let imageSource = ImageSource() {
      if let urlContents = try? Data(contentsOf: url) {
        return UIImage(data: urlContents)
      } else {
        return nil
      }
   }
  • Creates a new ImageSource that uses the provided generator to create the image.

    Effects: Creates the new image source.

    Declaration

    Swift

    public init(_ generator : @escaping () -> UIImage?)

    Parameters

    generator

    a function that returns a UIImage or nil, if a valid image cannot be created. The generator will be called at most, and only when the image property is accessed.

  • The image we are provided. Two notable aspects of the property:

    • It is lazy: We don’t call generator() until the first time the property is accessed.

    • It is private(set): This is a publicly readable property, but we can only modify it within the class!

    Declaration

    Swift

    private(set) public lazy var image: UIImage? { get set }
  • Declaration

    Swift

    public static func == (lhs: ImageSource, rhs: ImageSource) -> Bool

    Return Value

    true iff lhs and rhs are the same object.