0

The if let intensity = intensity {} else {} is repetitive. How would I create a function to replace this repetitive code? Or what other tool could I use?

I'm new to this all. Any help appreciated.

func process(filters: [String], intensity: Int? = nil) { for filter in filters { switch filter { case "blue": if let intensity = intensity { self.blue(value: intensity) } else { self.blue() } case "contrast": if let intensity = intensity { self.contrast(value: intensity) } else { self.contrast() } case "blackAndWhite": if let intensity = intensity { self.blackAndWhite(value: intensity) } else { self.blackAndWhite() } case "halfBrightness": if let intensity = intensity { self.halfBrightness(value: intensity) } else { self.halfBrightness() } case "doubleBrightness": if let intensity = intensity { self.doubleBrightness(value: intensity) } else { self.doubleBrightness() } default: print("The filter you specified doesn't exist.") } } } 

2 Answers 2

2

One possible option is to change all of those xxx(value:) methods so they accept an optional value. Let the implementation of each method deal with the optional value being nil as appropriate. Then each of your case statements becomes:

case "whatever": self.someFunction(value: intensity) 

Much cleaner.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use reflection to call the method based on the filter name, replacing all of the cases with a single block of code, with the added benefit that new filters added later will not require any change in this section of code.

Here's a starting point for you:

let selector_name = filter + ":" + (intensity != nil ? "_:" : "") let selector: Selector = Selector(selector_name) let method = class_getClassMethod(Test.self, selector) let implementation = method_getImplementation(method) typealias Function = @convention(c) (AnyObject, Selector, Int) -> Void let function = unsafeBitCast(implementation, to: Function.self) function(self, selector, intensity!) 

This code replaces your "switch" block. This isn't complete, since it doesn't handle your intensity == nil case, and it doesn't handle not finding the method that matches the filter name. And "Test.self" needs to be replaced with whatever you class name is, with the .self suffix. This is just intended to get you started.

You will probably take a performance hit, since using reflection usually does. Unless this code is being called many times per second, it should be insignificant.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.