I'm trying to write a Swift class (in Playground) that takes a dictionary of strings (such as PixelGreyScale
) and applies each sequentially to each pixel in an image.
I have it working with a dictionary of class methods, but it's very slow and I can't pass parameters.
In the code below, my class is instantiated and then the Process
method is run, taking in a dictionary of methods (a technique I saw on SO - is there a better way to dynamically run a method from a string variable?):
// Create an instance of the class, passing in the raw image
let p = ImageProcessor(src: rawImage);
// use a dictionary of method calls to queue up the process
let stack = [
{ p.PixelGreyScale() }
]
// run the process
p.Process(stack)
The Process
method calls each method in the stack and sets the current pixel to the return value:
func Process(stack: [() -> Pixel]) {
for y in 0..<rgba.height {
for x in 0..<rgba.width {
let index = y * rgba.width + x
currentIndex = index
rgba.pixels[index] = stack[0]()
}
}
}
This code runs, but I'm clearly not doing it right! I'm having the following problems:
- It takes an age to run, unless the
stack
dictionary is empty. Removing thestack[0]()
call doesn't speed things up - it seems that having something in the stack causes a slowdown when getting the pixel at a given index. - Because of how I'm using the
stack
dictionary to call methods, I can't pass parameters and have to resort to moving things into and out of class variables. I've tried usingperformSelector
but got exceptions every time I tried to use parameters.
Is there a way of passing in a dictionary of strings and using this to control which methods are executed, with parameters and without speed issues?