Created
October 4, 2016 15:45
-
-
Save soxjke/e92c4e090fbb5eaafc56ce51feb9beb5 to your computer and use it in GitHub Desktop.
Enum hell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //: Playground - noun: a place where people can play | |
| import Foundation | |
| import UIKit | |
| typealias ImagePostProcessingOp = (UIImage) -> Void | |
| enum ImageProcessor { | |
| case PostProcessOp(ImagePostProcessingOp) | |
| init(postProcessOp : ImagePostProcessingOp?) { | |
| if let postProcessOp = postProcessOp { | |
| self = .PostProcessOp(postProcessOp) | |
| } | |
| else { | |
| self = .PostProcessOp({_ in }) | |
| } | |
| } | |
| func processImage(original : UIImage) -> UIImage { | |
| switch self { | |
| case .PostProcessOp(let op): | |
| let image = original | |
| op(image) | |
| return image | |
| } | |
| } | |
| } | |
| enum Cacher { | |
| case Path(String) | |
| init(path : String) { | |
| self = Path(path) | |
| } | |
| func saveCachedImage(image : UIImage) { | |
| switch self { | |
| case .Path(let path): | |
| print("Saving image to \(path)") | |
| } | |
| } | |
| } | |
| enum Factory { | |
| case Factory1((ImagePostProcessingOp?) -> ImageProcessor, () -> Cacher) | |
| case Factory2((ImagePostProcessingOp?) -> ImageProcessor) | |
| init(ipGen : (ImagePostProcessingOp?) -> ImageProcessor, cacherGen : (() -> Cacher)? = nil) { | |
| if let cacherGen = cacherGen { | |
| self = .Factory1(ipGen, cacherGen) | |
| } | |
| else { | |
| self = .Factory2(ipGen) | |
| } | |
| } | |
| func generate() -> ImageProcessor { | |
| switch self { | |
| case .Factory1 (let ipGen, let cacherGen): | |
| return ipGen(cacherGen().saveCachedImage) | |
| case .Factory2(let ipGen): | |
| return ipGen(nil) | |
| } | |
| } | |
| } | |
| func validImageProcessor(postProcessingOp: ImagePostProcessingOp?) -> ImageProcessor { | |
| return ImageProcessor(postProcessOp: postProcessingOp) | |
| } | |
| func defaultCacher() -> Cacher { | |
| return Cacher(path: NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!) | |
| } | |
| Factory(ipGen: validImageProcessor, cacherGen: defaultCacher).generate().processImage(UIImage()) | |
| Factory(ipGen: validImageProcessor).generate().processImage(UIImage()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment